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

r"""
Update Package: 0XNVXA00
Dell Command | Update Windows Universal Application, 5.2.0, A00

General Usage: 
Dell-Command-Update-Windows-Universal-Application_0XNVX_WIN_5.2.0_A00.exe [/<option1>[=<value1>]] [/<option2>[=<value2>]]...
See listing below for <option> and <value> information.

NOTE:If the folder name contains space, double quotes should be given for folder name
EXAMPLE:/s /e="c:\Folder Name"

Option - Description:
---------------------
(none) - Display of graphical user interface for guided installation/update or extraction.

/? or /h - Displays this  Update Package usage information.

/s - Suppresses all graphical user interfaces of the  Update Package.

/e=<path> - Extraction of update contents to a folder.
(NOTE: Requires /s option)

/passthrough ... - (Advanced) Sends all text following the /passthrough option directly to the vendor install software of the  Update Package. This mode suppresses any  provided graphical user interfaces, but not necessarily those of the vendor software.

/factoryinstall /passthrough (vendor command line parameter) - (Advanced) (commnad line parameters) will be passed to vendor installer directly without parsing MUP.xml. Post installation, If the vendor installer returns REBOOT_REQUIRED or REBOOT_UPDATE_PENDING, it will be turned to SUCCESS.

/l=<path> - Define a specific path for the  Update Package log file.
(NOTE: This option can NOT be used in combination with /passthrough)


Example(s):
---------------------
Update the system silently
Dell-Command-Update-Windows-Universal-Application_0XNVX_WIN_5.2.0_A00.exe /s

Extract the update contents to the folder C:\mydir\
Dell-Command-Update-Windows-Universal-Application_0XNVX_WIN_5.2.0_A00.exe /s /e=C:\mydir

Pass command line arguments directly to vendor installer.
Turn the return code to success if required
Dell-Command-Update-Windows-Universal-Application_0XNVX_WIN_5.2.0_A00.exe /factoryinstall /passthrough D:\Sample.xml C:\log\FI.log


Change from the default log location to C:\my path with spaces\log.txt
Dell-Command-Update-Windows-Universal-Application_0XNVX_WIN_5.2.0_A00.exe /l="C:\my path with spaces\log.txt"


https://www.dell.com/support/manuals/en-us/command-update/dellcommandupdate_ug/silent-install?guid=guid-72c8f511-c7a5-4729-bf86-f92837841289&lang=en-us

"""


def install():
    bin_name = glob.glob("Dell-Command-Update-Windows-Universal-Application_*.EXE")[0]
    try:
        # Installing the software
        install_exe_if_needed(
            bin_name,
            silentflags=rf'/s /factoryinstall /passthrough /l="C:\Windows\Temp\%s"' % bin_name + ".log",
            name="Dell Command | Update for Windows Universal",
            min_version=control.get_software_version(),
            timeout=900,
        )

    except Exception as e:
        if e.returncode == 4:
            print(e)
            error(f"{control.name} cannot be installed because this PC is not a Dell Compatible System, please check: {control.sources}")
        else:
            error(e)

    # Disabling telemetry
    registry_set(HKEY_LOCAL_MACHINE, r"SOFTWARE\DELL\UpdateService\Clients\CommandUpdate\Preferences\Settings\General", "UserConsentDefault", 0)
    registry_set(HKEY_LOCAL_MACHINE, r"SOFTWARE\DELL\UpdateService\Clients\CommandUpdate\Preferences\CFG", "ShowSetupPopup", 0)

    # Download updates (notify when ready)
    registry_set(
        HKEY_LOCAL_MACHINE, r"SOFTWARE\DELL\UpdateService\Clients\CommandUpdate\Preferences\Settings\Schedule", "AutomationMode", "ScanDownloadNotify"
    )
    registry_set(HKEY_LOCAL_MACHINE, r"SOFTWARE\DELL\UpdateService\Clients\CommandUpdate\Preferences\Settings\Schedule", "ScheduleMode", "Auto")

    # # Manual updates only
    # registry_set(
    #     HKEY_LOCAL_MACHINE, r"SOFTWARE\DELL\UpdateService\Clients\CommandUpdate\Preferences\Settings\Schedule", "ScheduleMode", "ManualUpdates"
    # )

    # # Disable notification
    # registry_set(HKEY_LOCAL_MACHINE, r"SOFTWARE\DELL\UpdateService\Clients\CommandUpdate\Preferences\Settings\Schedule", "DisableNotification", 1)


def audit():
    audit_status = "OK"
    service_name = "DellClientManagementService"
    service_start_mode = get_service_start_mode(service_name)
    
    if not service_installed(service_name):
        print(f"{service_name} service does not exist.")
        audit_status = "ERROR"
    else:
        if service_start_mode in ["Disabled", "Manual"]:
            set_service_start_mode(service_name, "Auto")
        if not service_is_running(service_name):
            service_start(service_name)
        time.sleep(5)
        if not service_is_running(service_name):
            print(f"{service_name} service is not running.")
            audit_status = "WARNING"
        else:
            print(f"{service_name} service is working properly.")

            #write useful info in database
            catalog_timestamp = registry_readstring(HKEY_LOCAL_MACHINE,fr'SOFTWARE\Dell\UpdateService\Service','CatalogTimestamp')
            lastcheck_timestamp = registry_readstring(HKEY_LOCAL_MACHINE,fr'SOFTWARE\Dell\UpdateService\Service','LastCheckTimestamp')
            lastupdate_timestamp = registry_readstring(HKEY_LOCAL_MACHINE,fr'SOFTWARE\Dell\UpdateService\Service','LastUpdateTimestamp')
            pending_install = registry_readstring(HKEY_LOCAL_MACHINE,fr'SOFTWARE\Dell\UpdateService\Service\UpdateScheduler','PendingInstallPackages')
            info_list = ['CatalogTimestamp','LastCheckTimestamp','LastUpdateTimestamp','PendingInstallPackages']
            result_list = [catalog_timestamp,lastcheck_timestamp,lastupdate_timestamp,pending_install]
            audit_dict = dict(zip(info_list,result_list))
            print(audit_dict)
            WAPT.write_audit_data_if_changed("dell-command-update", "dell-command-update", audit_dict)


            audit_status = "OK"
            
    return audit_status


# def uninstall():
#     # Uninstalling the software
#     print("Uninstalling: %s" % control.package)
#     remove_appx("DellInc.DellCommandUpdate")
