#!/usr/bin/env bash
# gov-ctl.sh — Governor sauber starten/stoppen (Phase-0-Helfer).
# Nutzung:
#   gov-ctl.sh start [SCHWELLE]   # startet detached, Default-Schwelle 25000
#   gov-ctl.sh stop
#   gov-ctl.sh status
set -u
DIR="$HOME/governor-p0"
PIDF="$DIR/governor.pid"
LOG="$DIR/governor.log"
OUT="$DIR/governor.stdout"

start() {
  stop
  local thr="${1:-25000}"
  cd "$DIR"
  : > "$LOG"
  # Voll detachen: eigene Session, alle FDs weg vom Aufrufer.
  # Hart-Deckel nur setzen, wenn explizit uebergeben (Arg 2); sonst rechnet
  # governor.py den Default (Soft + 5000). CPT-Default 3.5 (kalibriert 24.07.).
  local hardenv=()
  if [ -n "${2:-}" ]; then hardenv=(GOV_HARD_CEILING="$2"); fi
  setsid env GOV_THRESHOLD="$thr" "${hardenv[@]}" \
    GOV_CHARS_PER_TOKEN="${GOV_CHARS_PER_TOKEN:-3.5}" \
    GOV_LOG="$LOG" GOV_PORT=8100 \
    python3 "$DIR/governor.py" </dev/null >>"$OUT" 2>&1 &
  echo $! > "$PIDF"
  sleep 1.2
  echo "started pid=$(cat "$PIDF") threshold=$thr hard=${2:-auto}"
  ss -tlnp 2>/dev/null | grep ":8100" >/dev/null && echo "listening :8100 OK" || echo "WARN: not listening"
}

stop() {
  pkill -f "$DIR/governor.py" 2>/dev/null || true
  [ -f "$PIDF" ] && kill "$(cat "$PIDF")" 2>/dev/null || true
  sleep 0.6
  rm -f "$PIDF"
}

status() {
  if pgrep -f "$DIR/governor.py" >/dev/null; then
    echo "running pid=$(pgrep -f "$DIR/governor.py" | tr '\n' ' ')"
    ss -tlnp 2>/dev/null | grep ":8100" || true
  else
    echo "not running"
  fi
}

case "${1:-status}" in
  start) shift; start "${1:-25000}" "${2:-}" ;;
  stop) stop; echo stopped ;;
  status) status ;;
  *) echo "usage: gov-ctl.sh {start [soft] [hart]|stop|status}"; exit 2 ;;
esac
