# -*- coding: utf-8 -*-
from setuphelpers import *
import json
import re
import requests


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

    # Getting latest version from official sources
    re_versions = re.compile(r'unbound_setup_(\d+\.\d+\.\d+)(?:-w32)?\.exe')
    index = wgets("https://www.nlnetlabs.nl/downloads/unbound/", proxies=proxies)

    for versionbutt in sorted(re_versions.findall(index), key=lambda p: (Version(p)), reverse=True):
        if control.architecture == "x86":
            latest_bin = "unbound_setup_%s-w32.exe" % versionbutt
            download_url = "https://www.nlnetlabs.nl/downloads/unbound/%s" % latest_bin

        if not requests.head(download_url, proxies=proxies).status_code == 404:
            version = versionbutt
            break

    # remove files
    for f in glob.glob("*.exe"):
        if f != latest_bin:
            remove_file(f)

    # Downloading latest binaries
    wget(download_url, latest_bin, proxies=proxies)

    control.set_software_version(version)
    control.save_control_to_wapt()
