import os
import re
import ctypes
from subprocess import PIPE, Popen

def ecmd(command):
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)

    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    if ret==0:
        if out:
            return out.strip()
        else:
            return ret
    else:
        if err:
            return err.strip()
        else:
            return ret


memory_size = ecmd(r'systeminfo | findstr /C:"Total Physical Memory"')
if memory_size:
    memory_size = ''.join(memory_size).split()[3]
    memory_size = str(int(memory_size.replace(",","")) / 1024)

ps_content=r'''

$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object Size, FreeSpace
"{0}" -f [math]::truncate($disk.FreeSpace / 1GB)

'''

file_name='powershell_file.ps1'
file_path=os.path.join(os.environ['TEMP'], file_name)
with open(file_path, 'wb') as wr:
    wr.write(ps_content)

ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
free_space = ecmd('powershell "%s"'%file_path)
os.remove(file_path)


if int(memory_size) > 2 and int(free_space) > 32:
    fromURL='https://go.microsoft.com/fwlink/?LinkID=799445'

    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                 self._revert(self.old_value)

    import subprocess
    import ssl
    with disable_file_system_redirection():
        import urllib
    Down_path=os.environ['PROGRAMDATA']
    fileName = 'Windows10Upgrade9252.exe'
    DownTo = os.path.join(Down_path, fileName)
    def downloadFile(DownTo, fromURL):
        try:
            with open(DownTo, 'wb') as f:
                try:
                    context = ssl._create_unverified_context()
                    f.write(urllib.urlopen(fromURL,context=context).read())
                except:
                    f.write(urllib.urlopen(fromURL).read())
            if os.path.isfile(DownTo):
                return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1000)
		
        except:
            return 'Please Check URL or Download Path!'

    if __name__=='__main__':
        print downloadFile(DownTo, fromURL )
        fileName = 'Windows10Upgrade9252.exe'

    LogDIR=os.environ['PROGRAMDATA']+r'\Windows10Upgradelogs'

    import shutil
    try:
        if os.path.exists(DownTo):
            ec='%s /quietinstall /skipeula /auto upgrade /copylogs %s'%(DownTo,LogDIR)
            OBJ = Popen(ec, shell = True, stdout = PIPE, stderr = PIPE)
            out, err = OBJ.communicate()
            RET = OBJ.returncode
            if RET == 0:
                print "Windows10 is Upgrading, It takes long time and automatically restarts the device"
            else:
                print "Windows10 is not Upgrading"

        else:
            print "Please check the path"
        
    except Exception as err :
        print err
	
    if os.path.exists(DownTo):
        os.remove(DownTo)
else:
    print "Windows Update Requires Minimum 2GB RAM and 32GB Free Disk Space"
