#!/usr/bin/env bash
# Install the homelab-context sync mechanism for the current OS.
# Called by bootstrap.sh; safe to re-run (idempotent).

set -euo pipefail

REPO_DIR="${HOMELAB_CONTEXT_DIR:-/opt/homelab-context}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

case "$(uname -s)" in
    Linux)
        install -m 0644 "$SCRIPT_DIR/linux/homelab-context-sync.service" \
            /etc/systemd/system/homelab-context-sync.service
        install -m 0644 "$SCRIPT_DIR/linux/homelab-context-sync.timer" \
            /etc/systemd/system/homelab-context-sync.timer
        systemctl daemon-reload
        systemctl enable --now homelab-context-sync.timer
        # Kick once so the first pull happens immediately.
        systemctl start homelab-context-sync.service || true
        echo "[install.sh] linux: timer installed and started"
        ;;
    Darwin)
        PLIST=/Library/LaunchDaemons/network.hubris.homelab-context-sync.plist
        install -m 0644 -o root -g wheel \
            "$SCRIPT_DIR/macos/network.hubris.homelab-context-sync.plist" "$PLIST"
        # Touch the log path so the daemon can write without a TOCTOU.
        touch /var/log/homelab-context-sync.log
        chmod 0644 /var/log/homelab-context-sync.log
        # bootstrap may have loaded a previous version; reload.
        launchctl bootout system "$PLIST" 2>/dev/null || true
        launchctl bootstrap system "$PLIST"
        launchctl enable system/network.hubris.homelab-context-sync
        # Kick once.
        launchctl kickstart -k system/network.hubris.homelab-context-sync || true
        echo "[install.sh] macos: launchd job loaded and kicked"
        ;;
    *)
        echo "[install.sh] unsupported OS: $(uname -s)" >&2
        exit 1
        ;;
esac
