# 此為刪除解除安裝時產生的殘留機碼

import errno

import os
import winreg

import re

proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()

# 設定要刪除目標機碼的值 Pattern (程式顯示的名稱)
target_pattern = re.compile(r'(Search App by Ask)|(Ask Toolbar)')

value = []

if proc_arch == 'x86' and not proc_arch64:
    arch_keys = {0}
elif proc_arch == 'x86' or proc_arch == 'amd64':
    arch_keys = {winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY}
else:
    raise Exception("Unhandled arch: %s" % proc_arch)


for arch_key in arch_keys:
    # 機碼路徑
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
                         0, winreg.KEY_ALL_ACCESS | arch_key)

    for i in range(0, winreg.QueryInfoKey(key)[0]):
        skey_name = winreg.EnumKey(key, i)
        skey = winreg.OpenKey(key, skey_name)
        try:
            target_name = winreg.QueryValueEx(skey, 'DisplayName')[0]

            if target_pattern.match(target_name):
                target_skey_name = skey_name

                for j in range(0, winreg.QueryInfoKey(skey)[1]):
                    winreg.DeleteValue(skey, winreg.EnumValue(skey, j)[0])
                    print(winreg.EnumValue(skey, j)[0])
        except OSError as e:
            if e.errno == errno.ENOENT:
                # DisplayName doesn't exist in this skey
                pass
        finally:

            skey.Close()
    if target_skey_name is not "":
        winreg.DeleteKey(key, target_skey_name)
    key.Close()
