Install_OR_Uninstall_OR_Update = 0 #give 0 to install, give 1 to uninstall, give 2 to update.

import os
import shutil
import ctypes

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)
            

def ecmd(command):
    from subprocess import PIPE, Popen
    
    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:
            print("ERROR!!!")
            return err.strip()
        else:
            return ret

def check():
    if os.path.exists(r"C:\ProgramData\chocolatey"):
        return 1
    else:
        return 0


def install():
    if check()==0:
        ps_content=r'''iex ((New-Object System.Net.WebClient).DownloadString("https://chocolatey.org/install.ps1"))'''
        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)  
        print(ecmd(r'powershell "Set-ExecutionPolicy RemoteSigned" && powershell -File "%s" > C:\Windows\temp\chocolog.txt && type C:\Windows\temp\chocolog.txt'%file_path))
    else:
        print("Already chocolatey installed")
        with disable_file_system_redirection():
            print(os.popen("choco").read())
        
        
def uninstall():
    if check()==1:
        try:
            shutil.rmtree(r"C:\ProgramData\chocolatey")
            print("successfully uninstalled the chocolatey")
        except Exception as e:
            print("got an error:\n%s"%(e))
    else:
        print("chocolatey is not installed on this machine")

def update():
    if check()==1:
        print(ecmd('choco upgrade chocolatey'))
    else:
        print("chocolatey is not installed on this machine. can't update when application is not installed")

if Install_OR_Uninstall_OR_Update==0:
    install()
elif Install_OR_Uninstall_OR_Update==1:
    uninstall()
elif Install_OR_Uninstall_OR_Update==2:
    update()