#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
# Parameter: Application_Name
# Example: "Google Chrome", "7-Zip", "Adobe Acrobat"

import _winreg
import subprocess
import time

app_name = itsm.getParameter('Application_Name')


UNINSTALL_KEYS = [
    r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
    r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
]


def find_msi_guids(name):
    matches = []

    for root in UNINSTALL_KEYS:
        try:
            key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, root)
            for i in range(_winreg.QueryInfoKey(key)[0]):
                try:
                    subkey_name = _winreg.EnumKey(key, i)
                    subkey = _winreg.OpenKey(key, subkey_name)

                    display, _ = _winreg.QueryValueEx(subkey, "DisplayName")

                    if name.lower() in display.lower():
                        if subkey_name.startswith("{") and subkey_name.endswith("}"):
                            matches.append(subkey_name)
                except:
                    pass
        except:
            pass

    return matches


def uninstall_msi(guid):
    cmd = [
        "msiexec",
        "/x", guid,
        "/qn",
        "/norestart"
    ]
    return subprocess.call(cmd)


guids = find_msi_guids(app_name)

if not guids:
    print("%s is not installed on the endpoint" % app_name)
else:
    for guid in guids:
        print("Found MSI GUID:", guid)
        print("Uninstalling %s ..." % app_name)

        exit_code = uninstall_msi(guid)
        time.sleep(10)

        if exit_code == 0:
            print("%s uninstalled successfully" % app_name)
        else:
            print("Uninstall failed for %s (Exit code: %s)" % (app_name, exit_code))
