import subprocess
import sys
import os

def get_debug_path():
    """Determine which debug path exists and return it."""
    paths = [
        "/Library/Application Support/com.comodo.osxclient",
        "/Library/Application Support/com.itarian.osxclient"
    ]
    for path in paths:
        if os.path.exists(path):
            return path
    print("Neither com.comodo.osxclient nor com.itarian.osxclient exists.")
    sys.exit(1)

def enable_debug_logging(debug_path):
    """Creates the debug_enabled file with sudo."""
    debug_file = os.path.join(debug_path, "debug_enabled")
    try:
        subprocess.check_call(["sudo", "touch", debug_file])
        print(f"Debug logging enabled successfully at {debug_file}")
    except subprocess.CalledProcessError as e:
        print("Failed to enable debug logging:", e)
        sys.exit(1)

def find_cdmdaemon_pid():
    """Finds the PID of cdmdaemon."""
    try:
        pid = subprocess.check_output(["pgrep", "cdmdaemon"]).decode().strip()
        if pid:
            print(f"cdmdaemon PID found: {pid}")
            return pid
        else:
            print("cdmdaemon is not running.")
            sys.exit(1)
    except subprocess.CalledProcessError:
        print("cdmdaemon process not found.")
        sys.exit(1)

def kill_cdmdaemon(pid):
    """Kills the cdmdaemon process using sudo kill -9."""
    try:
        subprocess.check_call(["sudo", "kill", "-9", pid])
        print(f"cdmdaemon (PID: {pid}) has been terminated.")
    except subprocess.CalledProcessError as e:
        print("Failed to kill cdmdaemon:", e)
        sys.exit(1)


debug_path = get_debug_path()
enable_debug_logging(debug_path)
cdmdaemon_pid = find_cdmdaemon_pid()
kill_cdmdaemon(cdmdaemon_pid)
