
import os
import ctypes
import urllib2
from subprocess import Popen, PIPE
import sys

exe_url = "https://script-downloads.itarian.com/DeskIn_Setup_v3.3.2.1_x64.exe" #chnage url you need to install other versions
exe_name = os.path.basename(exe_url)
exe_path = os.path.join(os.environ['TEMP'], exe_name)


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)

#Downloading File
def download_exe(url, save_path):
    try:
        print("Downloading setup file ......")
        response = urllib2.urlopen(url, timeout=60)
        with open(save_path, "wb") as f:
            f.write(response.read())
        print("Setup download completed")
        return save_path
    except Exception as e:
        print("Failed to download setup: %s" % str(e))
        return None

#silent install
def run_silent(installer_path):
    with disable_file_system_redirection():
        cmd = '"%s" /S' % installer_path
        print("Starting installation ......")
        obj = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
        out, err = obj.communicate()
        ret = obj.returncode
        if ret == 0:
            print("Installation completed")
            kill_task("DeskIn.exe")
        else:
            print("Installation failed with return code: %s" % ret)
            if err:
                print("Error: %s" % err)

def kill_task(process_name):
    with disable_file_system_redirection():
        cmd = 'taskkill /IM "%s" /F' % process_name
        os.system(cmd)


def main():
    print("Deskin Software Installation")

    # Step 1: Download installer
    downloaded_exe = download_exe(exe_url, exe_path)
    if not downloaded_exe:
        sys.exit(1)

    # Step 2: Run installer silently
    run_silent(downloaded_exe)


if __name__ == "__main__":
    main()
