#!/usr/bin/python3
"""
set_active_profile - Set which profile the daemon should run, and restart the daemon.

Input JSON (stdin):
  { "activeProfileId": 2 }        # set active profile
  { "activeProfileId": null }      # deactivate (no profile active)

This script:
  1. Reads the current config file.
  2. Updates the activeProfileId field.
  3. Writes the config back.
  4. Sends SIGHUP to the daemon (if running) so it picks up the change.
  5. If the daemon is not running and a profile is being activated, starts the service.
  6. If activeProfileId is null, stops the service.

Output (JSON to stdout):
  { "success": true, "daemonRunning": true }
"""

import json
import os
import signal
import subprocess
import sys

CONFIG_DIR  = "/etc/45drives/fan-controller"
CONFIG_PATH = os.path.join(CONFIG_DIR, "profiles.json")
SERVICE_NAME = "45d-fancontroller.service"


def main():
    try:
        data = json.loads(sys.stdin.read())
        new_active_id = data.get("activeProfileId")

        # Read existing config
        if os.path.isfile(CONFIG_PATH):
            with open(CONFIG_PATH, "r") as f:
                config = json.load(f)
        else:
            config = {"version": 1, "activeProfileId": None, "profiles": []}

        # Update active profile
        config["activeProfileId"] = new_active_id

        # Write back atomically
        os.makedirs(CONFIG_DIR, mode=0o755, exist_ok=True)
        tmp_path = CONFIG_PATH + ".tmp"
        with open(tmp_path, "w") as f:
            json.dump(config, f, indent=2)
            f.write("\n")
        os.rename(tmp_path, CONFIG_PATH)

        daemon_running = False

        if new_active_id is not None:
            # Activate: ensure daemon is running
            # Try SIGHUP first (reload config in running daemon)
            try:
                r = subprocess.run(
                    ["systemctl", "is-active", "--quiet", SERVICE_NAME],
                    timeout=5,
                )
                if r.returncode == 0:
                    # Daemon is running — send reload signal
                    subprocess.run(
                        ["systemctl", "reload-or-restart", SERVICE_NAME],
                        capture_output=True, text=True, timeout=15,
                    )
                    daemon_running = True
                else:
                    # Daemon not running — start it
                    subprocess.run(
                        ["systemctl", "start", SERVICE_NAME],
                        capture_output=True, text=True, timeout=15,
                    )
                    daemon_running = True
            except Exception as e:
                # Best-effort: daemon may fail to start on some systems
                daemon_running = False

            # Also enable the service so it starts on boot
            try:
                subprocess.run(
                    ["systemctl", "enable", SERVICE_NAME],
                    capture_output=True, text=True, timeout=10,
                )
            except Exception:
                pass
        else:
            # Deactivate: stop the daemon
            try:
                subprocess.run(
                    ["systemctl", "stop", SERVICE_NAME],
                    capture_output=True, text=True, timeout=15,
                )
                subprocess.run(
                    ["systemctl", "disable", SERVICE_NAME],
                    capture_output=True, text=True, timeout=10,
                )
            except Exception:
                pass
            daemon_running = False

        print(json.dumps({
            "success": True,
            "activeProfileId": new_active_id,
            "daemonRunning": daemon_running,
        }))

    except Exception as e:
        error = {"error_msg": str(e), "success": False}
        print(json.dumps(error), file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
