#!/bin/bash
# Install / uninstall / check the TVU host monitor launchd agent.
#
#   ./install.sh            install (or reinstall) and start it
#   ./install.sh uninstall  stop and remove it
#   ./install.sh status     is it loaded, and what did it last see
#
# A symlink is used rather than a copy so that editing the plist in this repo is
# the single way to change the schedule — no drifting duplicate under LaunchAgents.

set -uo pipefail

LABEL="com.tvu.host-monitor"
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="$REPO/launchd/$LABEL.plist"
DST="$HOME/Library/LaunchAgents/$LABEL.plist"
STATE_DIR="$HOME/.claude/host-monitor"

case "${1:-install}" in
  install)
    [ -f "$SRC" ] || { echo "missing $SRC"; exit 1; }
    mkdir -p "$STATE_DIR" "$HOME/Library/LaunchAgents"
    chmod +x "$REPO/bin/check-host.sh"

    # Fail loudly if the plist points somewhere else than this checkout — that
    # mismatch would silently monitor nothing after moving the repo.
    if ! grep -q "$REPO/bin/check-host.sh" "$SRC"; then
      echo "⚠️  $SRC does not reference $REPO/bin/check-host.sh"
      echo "    The repo has moved. Update the ProgramArguments path in the plist first."
      exit 1
    fi

    launchctl unload "$DST" 2>/dev/null   # ignore "not loaded"
    ln -sf "$SRC" "$DST"
    launchctl load "$DST" || { echo "launchctl load failed"; exit 1; }
    echo "✅ loaded $LABEL (every 15 min, runs once now)"
    echo "   state + log: $STATE_DIR"
    sleep 3
    echo ""
    echo "--- first run ---"
    tail -6 "$STATE_DIR/monitor.log" 2>/dev/null || echo "(no log yet; give it a few seconds)"
    ;;

  uninstall)
    launchctl unload "$DST" 2>/dev/null
    rm -f "$DST"
    echo "🗑  removed $LABEL (state and logs kept in $STATE_DIR)"
    ;;

  status)
    # Use `launchctl print`, NOT `launchctl list | grep -q`. With `set -o pipefail`,
    # `grep -q` exits on first match, `launchctl list` then dies of SIGPIPE, and the
    # non-zero pipeline made this report "loaded: no" for an agent that was in fact
    # registered and running. Found by actually running status after installing.
    if launchctl print "gui/$UID/$LABEL" >/dev/null 2>&1; then
      echo "loaded: yes"
      launchctl print "gui/$UID/$LABEL" 2>/dev/null \
        | grep -E '^[[:space:]]*(state|last exit code|run interval) ' | sed 's/^[[:space:]]*/  /'
    else
      echo "loaded: no"
    fi
    echo ""
    echo "current state:"
    if [ -s "$STATE_DIR/state" ]; then sed 's/^/  /' "$STATE_DIR/state"; else echo "  (none yet)"; fi
    echo ""
    if [ -f "$STATE_DIR/ALERT.txt" ]; then
      echo "⚠️  ACTIVE ALERT:"; sed 's/^/  /' "$STATE_DIR/ALERT.txt"
    else
      echo "no active alert"
    fi
    echo ""
    echo "last checks:"
    tail -8 "$STATE_DIR/monitor.log" 2>/dev/null | sed 's/^/  /' || echo "  (no log)"
    ;;

  *)
    echo "usage: $0 [install|uninstall|status]"; exit 1 ;;
esac
