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

bin_contains = "TortoiseGit-"


def update_package():
    # Initializing variables
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    url = "https://tortoisegit.org/download/"
    if control.architecture == "x64":
        arch = "64bit"
    else:
        arch = "32bit"

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "a", "class", "dl", proxies=proxies):
        if bin_contains in bs_search["href"] and arch in bs_search["href"]:
            version = bs_search["href"].split("/")[-2]
            latest_bin = bs_search["href"].split("/")[-1]
            url_dl = "https:" + bs_search["href"]
            break

    print("Latest %s version is: %s" % (app_name, version))
    print("Download url is: %s" % url_dl)

    # Downloading latest binaries
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(url_dl, latest_bin, proxies=proxies)

        # Checking version from file
        version_from_file = get_version_from_binary(latest_bin)
        if version != version_from_file and version_from_file != "":
            print("Changing version to the version number of the binary (from: %s to: %s)" % (version, version_from_file))
            os.rename(latest_bin, latest_bin.replace(version, version_from_file))
            version = version_from_file

    # Changing version of the package
    control.version = "%s-%s" % (version, control.version.split("-", 1)[-1])
    control.save_control_to_wapt()

    # Deleting outdated binaries
    remove_outdated_binaries(version, filename_contains=arch)
