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

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

    # Sources
    download_url = "https://download.anydesk.com/anydesk.dmg"
    latest_bin = download_url.split("/")[-1]

    # Deleting binaries
    remove_outdated_binaries("*")

    # Downloading
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)

    # Monte le DMG => extrait AnyDesk.app
    # defaults read Info.plist => Lit "Version: 8.0.11" 
    # hdiutil detach => Démonte/nettoie
    version = "0.0.0"
    try:
        mount_point = "/tmp/anydesk_mount"
        run(f"hdiutil attach '{latest_bin}' -mountpoint {mount_point} -nobrowse -quiet")

        plist_path = f"{mount_point}/AnyDesk.app/Contents/Info.plist"
        if isdir(f"{mount_point}/AnyDesk.app"):
            version_cmd = f"defaults read '{plist_path}' CFBundleShortVersionString 2>/dev/null"
            version_output = run(version_cmd, shell=True)
            if version_output.strip():
                version = version_output.strip()

        # Clean
        run(f"hdiutil detach {mount_point} -quiet")
        print(f"Version détectée: {version}")

    except Exception as e:
        print(f"Erreur mount: {e}")

    # Update package
    if Version(version) > Version(control.get_software_version()):
        print("Software version updated")
        package_updated = True

    control.set_software_version(version)
    control.save_control_to_wapt()
    return package_updated