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

def update_package():

    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    url = 'https://www.xenserver.com/downloads'
    for bs_search in bs_find_all(url, "a", "class", "ctx-download ctx-button primary ctx-blue", proxies=proxies):
        if 'XenCenter' in bs_search['href']:
            download_url = bs_search['href']
            break
    latest_bin = download_url.split('/')[-1]
    version = download_url.split('/')[-2]

    # Downloading latest binaries
    print("Latest %s version is: %s" % (control.name, version))
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

    for f in glob.glob('*.msi'):
        if f != latest_bin:
            remove_file(f)

    # Changing version of the package
    if Version(version, 4) > Version(control.get_software_version(), 4):
        print("Software version updated (from: %s to: %s)" % (control.get_software_version(), Version(version)))
        package_updated = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating or not update-package-sources
    return package_updated
