# -*- coding: UTF-8 -*-
from setuphelpers import *
import platform

r"""

Installation procedure: https://firefox-source-docs.mozilla.org/browser/installer/windows/installer/FullConfig.html

"""
# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls

silent_args = "/S /PreventRebootRequired=false /TaskbarShortcut=false /DesktopShortcut=false /StartMenuShortcut=true /MaintenanceService=false /RegisterDefaultAgent=false /RemoveDistributionDir=false /OptionalExtensions=false"
list_lang = ["it", "fr", "en-US", "es-ES", "de"]
policies_path = makepath(programfiles, "Mozilla Thunderbird", "distribution", "policies.json")


def install():
    # Initializing variables
    package_version = control.get_software_version()
    bin_name = glob.glob('*.exe')[0]

    # Translating arch
    if iswin64():
        app_arch = "x64"
        arch_to_uninstall = "x86"
    elif iswinarm():
        app_arch = "arm"
        arch_to_uninstall = None
    else:
        app_arch = "x86"
        arch_to_uninstall = "x64"
        
    # Translating locale
    for lang in list_lang:
        if control.locale in lang:
            locale = lang

    app_uninstallkey = "Mozilla Thunderbird %s ESR (%s %s)" % (package_version, app_arch, locale)

    # Uninstalling others versions
    for uninstall in installed_softwares(name="Mozilla Thunderbird"):
        if arch_to_uninstall and (arch_to_uninstall in uninstall["name"] or (not "ESR" in uninstall["name"])):
            print("Removing: %s" % (uninstall["name"]))
            killalltasks(ensure_list(control.impacted_process))
            run(uninstall_cmd(uninstall["key"]))
            wait_uninstallkey_absent(uninstall["key"])

    # Installing the package
    print("Installing: %s" % bin_name)
    install_exe_if_needed(bin_name, silentflags=silent_args, key=app_uninstallkey, min_version=package_version)

    # Making sure that Mozilla Maintenance Service is not installed
    for uninstall in installed_softwares(name="Mozilla Maintenance Service"):
        print("Removing: %s" % (uninstall["name"]))
        run(uninstall_cmd(uninstall["key"]))

    # Adding Minimal configuration for Thunderbird you may use the package "tis-config-thunderbird" for further options
    if not isfile(policies_path):
        registry_set(HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\Mozilla\Thunderbird", "DisableAppUpdate", 1, REG_DWORD)
        registry_set(HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\Mozilla\Thunderbird", "DisableTelemetry", 1, REG_DWORD)

def iswinarm():
    return platform.machine() =='ARM64'