# -*- coding: utf-8 -*-
from setuphelpers import *

# OpenVPN.GUI,OpenVPN.Service,OpenVPN.Documentation,OpenVPN.SampleCfg,Drivers.OvpnDco,OpenSSL,EasyRSA,OpenVPN,OpenVPN.GUI.OnLogon,OpenVPN.PLAP.Register,Drivers,Drivers.TAPWindows6,Drivers.Wintun
properties = {}
#    "ADDLOCAL": "OpenVPN.GUI,OpenVPN.Service,OpenVPN,Drivers,Drivers.Wintun,Drivers.TAPWindows6,Drivers.OvpnDco"
#}  # ,OpenVPN.GUI.OnLogon,Drivers.OvpnDco


def install():
    # declaring local variables
    bin_name = glob.glob("OpenVPN-*.msi")[0]

    # Uninstalling specific versions of the software
    for to_uninstall in installed_softwares(name="OpenVPN "):
        if Version(to_uninstall["version"]) > Version("2.6") and Version(to_uninstall["version"]) <= Version("2.6.010"):
            print("Removing: %s (%s)" % (to_uninstall["name"], to_uninstall["version"]))
            killalltasks(control.get_impacted_process_list())
            run(uninstall_cmd(to_uninstall["key"]))
            wait_uninstallkey_absent(to_uninstall["key"])

    # adding "OpenVPN Inc."" and "WireGuard LLC" trusted driver certificates
    try:
        run('"%s" -addstore TrustedPublisher "%s"' % (makepath(system32, "certutil.exe"), makepath(basedir, "openvpn.cer")), timeout=60)
        run('"%s" -addstore TrustedPublisher "%s"' % (makepath(system32, "certutil.exe"), makepath(basedir, "wireguard.cer")), timeout=60)
    except:
        print("WARNING: Required Publisher Driver certificates have not been applied, you may need to apply them manually or with GPO")

    # installing the package
    install_msi_if_needed(
        bin_name,
        properties=properties,
        min_version=get_msi_properties(bin_name)["ProductVersion"],
    )

    # Removing application's desktop shortcut if allowed
    if params.get("remove_desktop_shortcut"):
        remove_desktop_shortcut("OpenVPN GUI")
        
    # Disabling autostart at start up
    if reg_value_exists(HKEY_CURRENT_USER, makepath('Software', 'Microsoft', 'Windows', 'CurrentVersion', 'Run'), 'OpenVPN-GUI'):
        print('Disabling autostart')
        registry_delete(HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Run', 'OpenVPN-GUI')

def uninstall():
    # removing "OpenVPN Inc." and "WireGuard LLC" trusted driver certificates
    try:
        run('"%s" -delstore TrustedPublisher "OpenVPN Inc."' % (makepath(system32, "certutil.exe")), timeout=60)
        run('"%s" -delstore TrustedPublisher "WireGuard LLC"' % (makepath(system32, "certutil.exe")), timeout=60)
    except:
        print("WARNING: Driver certificates have not been removed")
