url="https://bluebook.app.collegeboard.org/downloads/Bluebook%20Setup%200.9.175.exe" # give here the direct download link of the updated version of bluebook application

import os
from subprocess import PIPE, Popen
import ctypes
import ssl
import urllib2
import time

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)
    
    
Down_path=os.environ['TEMP']
fileName = "Bluebook.exe"
DownTo = os.path.join(Down_path, fileName)

def ecmd(command):   
    from subprocess import Popen, PIPE
    import ctypes
    
    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

def downloadFile(DownTo, fromURL):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
    context = ssl._create_unverified_context()
    request = urllib2.Request(fromURL, headers=headers)
    req = urllib2.urlopen(request,context=context)
    try:
        with open(DownTo, 'wb') as f:
            while True:
                chunk = req.read(100*1000*1000)
                if chunk:
                    f.write(chunk)
                else:
                    break
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1024)
		
    except:
        return 'Please Check URL or Download Path!'
        


def install():
    with disable_file_system_redirection():
        print(ecmd("%s /S"%(DownTo)))
        os.remove(DownTo)
        
def uninstall():
    with disable_file_system_redirection():
        query = os.popen("REG QUERY HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\").read()        
        for i in query.splitlines():
            displayname = os.popen('REG QUERY "%s" /v DisplayName'%(i)).read()
            if "Bluebook" in displayname:
                print("Bluebook application is found on this machine. checking the version.....")
                print(downloadFile(DownTo, url))
                versioninfo = os.popen('wmic datafile where name="%s" get Version /value'%("\\\\".join(DownTo.split("\\")))).read()
                version = versioninfo.split("=")[-1].strip()
                appPath = os.environ["LOCALAPPDATA"] + r"\Programs\bluebook\Bluebook.exe"
                installedversion = os.popen('wmic datafile where name="%s" get Version /value'%("\\\\".join(appPath.split("\\")))).read().split("=")[-1].strip()
                if version>installedversion:
                    print("installed version of the application is old. updating to the new version")
                    uninstallstringQuery = os.popen('REG QUERY "%s" /v QuietUninstallString'%(i)).read().split("REG_SZ")[-1].strip()
                    print(ecmd("%s"%(uninstallstringQuery)))
                    return 0
                elif version==installedversion:
                    print("bluebook application on this machine is already updated to new version")
                    return 1
                elif installedversion>version:
                    print("given link for the bluebook application is older than the installed version. please give the link of updated version of the application")
                    return 1
        else:
            print("bluebook application is not found on this machine. installing bluebook application....")
            return 2
        

def update():
    with disable_file_system_redirection():
        returncode = uninstall()
        if returncode == 0:
            time.sleep(10)
            install()
        elif returncode==1:
            os.remove(DownTo)
        elif returncode==2:
            print(downloadFile(DownTo, url))
            install()

update()
