#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import os
import ctypes
from subprocess import Popen, PIPE
import sys
import _winreg as reg  # Python 2.7

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 get_uninstall_string(software_name):
    """
    Search registry for the uninstall string for a given software
    """
    uninstall_paths = [
        r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
        r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
    ]

    for path in uninstall_paths:
        try:
            reg_key = reg.OpenKey(reg.HKEY_LOCAL_MACHINE, path)
            for i in range(0, reg.QueryInfoKey(reg_key)[0]):
                subkey_name = reg.EnumKey(reg_key, i)
                subkey = reg.OpenKey(reg_key, subkey_name)
                try:
                    display_name = reg.QueryValueEx(subkey, "DisplayName")[0]
                    if software_name.lower() in display_name.lower():
                        uninstall_str = reg.QueryValueEx(subkey, "UninstallString")[0]
                        return uninstall_str
                except WindowsError:
                    continue
        except WindowsError:
            continue
    return None

def run_uninstall(uninstall_cmd):
    with disable_file_system_redirection():
        # Ensure silent uninstall flags
        if uninstall_cmd.lower().endswith(".exe"):
            cmd = '"%s" /S' % uninstall_cmd
        elif "msiexec" in uninstall_cmd.lower():
            cmd = uninstall_cmd + " /qn"
        else:
            cmd = uninstall_cmd

        print("Starting uninstall: %s" % cmd)
        obj = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
        out, err = obj.communicate()
        ret = obj.returncode
        if ret == 0:
            print("Uninstallation completed")
        else:
            print("Uninstallation failed with return code: %s" % ret)
            if err:
                print("Error: %s" % err)

def main():
    software_name = "DeskIn"  # Change if needed
    uninstall_str = get_uninstall_string(software_name)
    if not uninstall_str:
        print("Could not find uninstall string for %s" % software_name)
        sys.exit(1)
    run_uninstall(uninstall_str)

if __name__ == "__main__":
    main()
