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

def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()
    app_name = control.name

    api_url = "https://api.github.com/repos/gitextensions/gitextensions/releases/latest"

    # Getting latest version information from official sources
    print(f"API used is: {api_url}")
    json_load = wgets(api_url, proxies=proxies, as_json=True)
    version = json_load["tag_name"].replace("v", "")
    for to_download in json_load["assets"]:
        if to_download["name"].startswith('GitExtensions-x64') and to_download["name"].endswith('.msi'):
            download_url = to_download["browser_download_url"]
            latest_bin = to_download["name"]
            break

    # Downloading latest binaries
    print(f"Latest {app_name} version is: {version}")
    print(f"Download URL is: {download_url}")
    if not isfile(latest_bin):
        print(f"Downloading: {latest_bin}")
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print(f"Binary is present: {latest_bin}")

    # Deleting outdated binaries
    for f in glob.glob('*.msi'):
        if Version(get_version_from_binary(f)) < Version(version):
            remove_file(f)

    # Free Code Signing for Open Source software : https://signpath.org/
    expected_issuer = 'SignPath Foundation'
    sign_name = waptlicences.check_msi_signature(latest_bin)[0]
    if sign_name != expected_issuer:
        error(f'Bad issuer {sign_name} != {expected_issuer} ')

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print(f"Software version updated (from: {control.get_software_version()} to: {version})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({version})")

    control.set_software_version(get_version_from_binary(latest_bin))
    control.save_control_to_wapt()

    # Validating update-package-sources
    return package_updated