import glob
import os
import shutil
import subprocess
import sys
import datetime

URL = "https://script-downloads.itarian.com/MacOS_CCS/CCS_2.6.1.1160.dmg"
WORK_DIR = "/private/tmp/temp_CCS"
MOUNT_DIR = WORK_DIR + "/mnt"
DMG = WORK_DIR + "/" + URL.split("/")[-1]
INSTALLER = MOUNT_DIR + "/Install Xcitium Client - Security.app/Contents/MacOS/Install Xcitium Client - Security"
UNINSTALLER = MOUNT_DIR + "/Uninstall Xcitium Client - Security.app/Contents/MacOS/Uninstall Xcitium Client - Security"
LOG_FILE = "/private/tmp/ccs_install.log"


def log(level, msg):
    line = "%s [%s] %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), level, msg)
    print(line, flush=True)
    with open(LOG_FILE, "a") as f:
        f.write(line + "\n")


def run(cmd):
    p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
    return p.returncode, p.stdout.strip()


def existing_clients():
    return glob.glob("/Applications/* Client - Security.app")


def cleanup():
    run(["hdiutil", "detach", "-force", "-quiet", MOUNT_DIR])
    shutil.rmtree(WORK_DIR, ignore_errors=True)


def main():
    ver = run(["sw_vers", "-productVersion"])[1]
    major = int(ver.split(".")[0])
    log("INFO", "macOS version: " + ver)
    if major not in (12, 13):
        log("INFO", "macOS %d is not 12.x or 13.x, skipping XCSM 2.6.1" % major)
        return 1

    if os.geteuid() != 0:
        log("ERROR", "Must run as root")
        return 2

    shutil.rmtree(WORK_DIR, ignore_errors=True)
    os.makedirs(MOUNT_DIR)

    log("INFO", "Downloading " + URL)
    rc, out = run(["curl", "-fL", "--retry", "3", "-o", DMG, URL])
    if rc != 0 or not os.path.isfile(DMG) or os.path.getsize(DMG) < 1000000:
        log("ERROR", "Download failed (rc=%d): %s" % (rc, out))
        return 2
    log("INFO", "Downloaded %d KB" % (os.path.getsize(DMG) // 1024))

    rc, out = run(["hdiutil", "attach", "-nobrowse", "-mountpoint", MOUNT_DIR, DMG])
    if rc != 0:
        log("ERROR", "Mount failed: " + out)
        return 2

    if not os.path.isfile(INSTALLER) or not os.path.isfile(UNINSTALLER):
        log("ERROR", "Installer or uninstaller not found in DMG")
        return 2

    found = existing_clients()
    if found:
        log("INFO", "Existing client found: %s - uninstalling first" % ", ".join(found))
        rc, out = run([UNINSTALLER, "--silent"])
        log("INFO", out)
        if rc != 0:
            log("ERROR", "Uninstall failed, exit code %d" % rc)
            return 2

    log("INFO", "Installing XCSM 2.6.1.1160")
    rc, out = run([INSTALLER, "--silent"])
    log("INFO", out)
    if rc != 0:
        log("ERROR", "Install failed, exit code %d" % rc)
        return 2

    if not os.path.isdir("/Applications/Xcitium Client - Security.app"):
        log("ERROR", "Install reported success but app not found")
        return 2

    log("INFO", "XCSM 2.6.1.1160 installed successfully")
    return 0


if __name__ == "__main__":
    try:
        code = main()
    except Exception as e:
        log("CRITICAL", "Unhandled exception: " + str(e))
        code = 3
    finally:
        cleanup()
    sys.exit(code)