import os
import ssl
import urllib2
from subprocess import Popen, PIPE
import _winreg as reg  # for Python 2

# Constants
UNINSTALL_TOOL_URL = r"https://script-downloads.itarian.com/Bitdefender_Uninstall_Tool/BEST_UninstallTool.exe"
TEMP = os.environ.get('TEMP') or os.environ.get('TMP') or r"C:\Windows\Temp"
UNINSTALL_EXE = os.path.join(TEMP, "BEST_uninstallTool.exe")
WRAPPER_LOG = os.path.join(TEMP, "bd_uninstall_wrapper.log")
REBOOT_REQUIRED = 3010

def download_tool(url, dest):
    req = urllib2.Request(url, headers={'User-Agent': "Mozilla/5.0"})
    try:
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        resp = urllib2.urlopen(req, context=ctx)
    except Exception:
        resp = urllib2.urlopen(req)
    with open(dest, "wb") as f:
        while True:
            chunk = resp.read(1024 * 1024)
            if not chunk:
                break
            f.write(chunk)
    return dest

def run_uninstall():
    cmd = '"{0}" /bdparams /bruteForce /log /noWait'.format(UNINSTALL_EXE)
    proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    ret = proc.returncode

    with open(WRAPPER_LOG, "a") as logf:
        logf.write("Command: {0}\n".format(cmd))
        logf.write("ExitCode: {0}\n".format(ret))
        if out:
            logf.write("Out: {0}\n".format(out))
        if err:
            logf.write("Err: {0}\n".format(err))

    return ret, out, err

def check_registry_uninstalled():
    key_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Endpoint Security"
    try:
        reg.OpenKey(reg.HKEY_LOCAL_MACHINE, key_path, 0, reg.KEY_READ)
        return False
    except WindowsError:
        return True

def main():
    download_tool(UNINSTALL_TOOL_URL, UNINSTALL_EXE)
    print("Downloaded uninstall tool to:", UNINSTALL_EXE)

    exit_code, out, err = run_uninstall()

    # Decide status
    if exit_code == 0:
        status = "SUCCESS"
        note = "No reboot required."
    elif exit_code == REBOOT_REQUIRED:
        status = "SUCCESS"
        note = "Reboot required (exit code {}).".format(REBOOT_REQUIRED)
    else:
        status = "FAILURE"
        note = "Unexpected exit code: {}".format(exit_code)

    uninstalled = check_registry_uninstalled()
    with open(WRAPPER_LOG, "a") as logf:
        logf.write("Registry uninstalled: {0}\n".format(uninstalled))
        logf.write("Final status: {0} — {1}\n".format(status, note))

    print("Uninstall status:", status)
    print(note)

    # Return 0 for both success cases (including reboot-required)
    if status == "SUCCESS":
        return 0
    else:
        return 1

if __name__ == "__main__":
    import sys
    sys.exit(main())
