# -*- coding: utf-8 -*-
import os
import subprocess
import ctypes
import time
import sys

# Bluebeam GUIDs
GUID_OCR  = "{93315BA6-A757-4D3D-84BE-4F2C244A4464}"
GUID_REVU = "{99588A9A-57A2-4807-9B55-6CB84E83FECA}"

# Disable WOW64 Redirection
class disable_fs_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, a, b, c):
        if self.success:
            self._revert(self.old_value)

# Run a command
def run(cmd):
    with disable_fs_redirection():
        p = subprocess.Popen(cmd, shell=True)
        p.wait()
        return p.returncode

# Uninstall by GUID (NOW FAILS if exit code ≠ 0)
def uninstall_simple(name, guid):
    print("Uninstalling %s started" % name)
    cmd = 'msiexec /x %s /qn /norestart' % guid
    exit_code = run(cmd)
    time.sleep(3)
    print("Exit code: %s" % exit_code)

    # If uninstall fails → EXIT SCRIPT with failure
    if exit_code != 0:
        print("Uninstallation failed for %s. Stopping script." % name)
        sys.exit(exit_code)

# Delete registry key
def reg_delete(path):
    cmd = 'reg delete "%s" /f' % path
    run(cmd)

# -----------------------------
# MAIN PROCESS
# -----------------------------

# Uninstall OCR
uninstall_simple("Bluebeam OCR 21", GUID_OCR)

# Uninstall Revu
uninstall_simple("Bluebeam Revu 21", GUID_REVU)

print("Registry cleanup started")

reg_delete("HKEY_LOCAL_MACHINE\\SOFTWARE\\Bluebeam Software")
reg_delete("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Bluebeam Software")
reg_delete("HKEY_CURRENT_USER\\Software\\Bluebeam Software")
reg_delete("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s" % GUID_OCR)
reg_delete("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s" % GUID_REVU)

print("Registry cleanup complete")
print("Bluebeam complete removal finished")
