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

r"""
{
    "key": "Linphone",
    "name": "Linphone",
    "version": "5.1.2",
    "install_date": "",
    "install_location": "",
    "uninstall_string": "C:\\Program Files\\Linphone\\Uninstall.exe",
    "publisher": "Belledonne Communications",
    "system_component": 0,
    "win64": false,
}

Name,Group,Profile,Enabled,Action,Override,Program,Local Address,Remote Address,Protocol,Local Port,Remote Port,Authorized Users,Authorized Computers,Authorized Local Principals,Local User Owner,PolicyAppId,Application Package,
Linphone - A libre SIP client,,Domain,Yes,Allow,No,C:\program files\linphone\bin\linphone.exe,Any,Any,UDP,Any,Any,Any,Any,Any,Any,None,Any,
Linphone - A libre SIP client,,Domain,Yes,Allow,No,C:\program files\linphone\bin\linphone.exe,Any,Any,TCP,Any,Any,Any,Any,Any,Any,None,Any,

"""


def get_version(app_registry_dict):
    app_dir = os.path.dirname(app_registry_dict['uninstall_string'])
    version = get_version_from_binary(makepath(app_dir, 'bin', 'linphone.exe'), property_name="FileVersion")
    return version


def install():
    # Declaring local variables
    bin_name = glob.glob("Linphone-*-win64.exe")[0]

    # Uninstall the older versions of the software  # it seems necessary for Linphone
    for to_uninstall in installed_softwares(uninstallkey="Linphone"):

        app_dir = os.path.dirname(to_uninstall['uninstall_string'])
        app_version = get_version_from_binary(makepath(app_dir, 'bin', 'linphone.exe'), property_name="FileVersion")

        if Version(app_version) < Version(control.get_software_version()) or force:
            print("Removing: %s (%s)" % (to_uninstall["name"], to_uninstall["version"]))
            killalltasks(ensure_list(control.impacted_process))
            run(uninstall_cmd(to_uninstall["key"]))
            wait_uninstallkey_absent(to_uninstall["key"])

    # Installing the software
    install_exe_if_needed(
        bin_name,
        silentflags="/S",
        key="Linphone",
        get_version=get_version,
        min_version=control.get_software_version(),
    )

    # Adding Firewall Rules
    app_path = makepath(os.path.dirname(installed_softwares(uninstallkey="Linphone")[0]["uninstall_string"]), "bin", "linphone.exe")
    remove_netfirewallrule("Linphone - A libre SIP client")
    add_netfirewallrule("Linphone - A libre SIP client", app_path, profile="Domain,Private", protocol="UDP")
    add_netfirewallrule("Linphone - A libre SIP client", app_path, profile="Domain,Private", protocol="TCP")


def uninstall():
    # Removing Firewall Rules
    remove_netfirewallrule("Linphone - A libre SIP client")