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

r"""
Usable WAPT package functions: install(), uninstall(), session_setup(), audit(), update_package()
 {
   "key":"{C71C4442-CA69-443C-AFC1-53E0D4AD7D1A}",
   "name":"Charles 4.6.6",
   "version":"4.6.6.0",
   "install_date":"2024-05-16 00:00:00",
   "install_location":"",
   "uninstall_string":"MsiExec.exe /X{C71C4442-CA69-443C-AFC1-53E0D4AD7D1A}",
   "publisher":"XK72 Ltd",
   "system_component":0,
   "win64":true
  }

"""
# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls


def install():
    # Declaring local variables
    bin_name = glob.glob("*.dmg")[0]


    def mount_dmg(dmg_path):
        """Mounts a dmg file.

        Returns: The path to the mount point.
        """
        try:
            return run("yes | hdiutil mount '" + dmg_path + "'").split("\t")[-1].rstrip()
        except subprocess.CalledProcessError as e:
            raise Exception("Error in mount_dmg : {0}".format(e.output))

    def install_dmg(dmg_path, key="", min_version="", get_version=None, force=False, killbefore=None, uninstallkeylist=None):
        """Installs a .dmg if it isn't already installed on the system.

        Arguments:
            dmg_path : the path to the dmg file

        Returns:
            True if it succeeded, False otherwise
        """
        ret_val = True

        dmg_name = os.path.basename(dmg_path)
        dmg_mount_path = mount_dmg(dmg_path)

        try:
            dmg_file_assoc = {".pkg": install_pkg, ".mpkg": install_pkg, ".app": install_app}
            files = [dmg_mount_path + "/" + fname for fname in os.listdir(dmg_mount_path)]
            nb_files_handled = 0
            for file in files:
                fname, fextension = os.path.splitext(file)
                if fextension in dmg_file_assoc:
                    dmg_file_assoc[fextension](
                        file,
                        key=key,
                        min_version=min_version,
                        get_version=get_version,
                        force=force,
                        uninstallkeylist=uninstallkeylist,
                        killbefore=killbefore,
                    )
                    nb_files_handled += 1

            if nb_files_handled == 0:
                error("Error : the dmg provided did not contain a package or an application, or none could be found.")

            unmount_dmg(dmg_mount_path)
        except Exception as e:
            unmount_dmg(dmg_mount_path)
            raise


    # Installing the software
    install_dmg(bin_name,
        key='/Applications/Charles.app',
        min_version=control.get_software_version()
    )

def uninstall():
    if isdir('/Applications/Charles.app'):
        remove_tree('/Applications/Charles.app')


