#!/usr/bin/env bash
# parvagues-gear — pause/resume the whole ParVagues rig as one unit.
#
# Why: the gear set autostarts at login and runs forever — sclang+scsynth burn
# ~2.6W idle, and midi-autoconnect / tidal-ardour-autoroute poll every 2s.
# On battery (esp. this worn pack) that's real minutes. There was no "off".
#
# THE UNIT LIST IS NOT AUTHORED HERE. tools/rig_units.py owns it (the
# "list lived in three places" lesson); this script derives its sets from
# `rig_units.py --list`. Adding a unit to the rig = one row there, and gear
# pauses/resumes it with no edit here. "manual"-policy units (the v2 LED
# watcher) are paused if running but never resumed — resuming one would
# Conflicts=-kill the LCXL3 driver.
#
# ORDER MATTERS: parvagues-sc-watchdog is Restart=always and exists to restart
# SC when scsynth dies. Stop the watchdog FIRST or it resurrects SC; on resume,
# start SC FIRST so the watchdog doesn't race it.
set -euo pipefail

DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)"

WATCHDOG=parvagues-sc-watchdog
SC=parvagues-sc
REST=()          # startable units minus SC + watchdog (order handled above)
MANUAL=()        # never resumed; paused only if running
while IFS= read -r u; do
  [[ $u == "$SC" || $u == "$WATCHDOG" ]] && continue
  REST+=("$u")
done < <(python3 "$DIR/tools/rig_units.py" --list --boot auto)
while IFS= read -r u; do MANUAL+=("$u"); done \
  < <(python3 "$DIR/tools/rig_units.py" --list --boot manual)
ALL=("$WATCHDOG" "$SC" "${REST[@]}" "${MANUAL[@]}")

pwr() {
  local c v
  c=$(cat /sys/class/power_supply/BAT0/current_now 2>/dev/null) || return 0
  v=$(cat /sys/class/power_supply/BAT0/voltage_now)
  awk -v c="$c" -v v="$v" 'BEGIN{printf "%.1fW", c/1e6*v/1e6}'
  echo " · battery $(cat /sys/class/power_supply/BAT0/capacity)%"
}

case "${1:-status}" in
  pause)
    systemctl --user stop "$WATCHDOG"          # before SC, or it restarts it
    systemctl --user stop "$SC" "${REST[@]}" "${MANUAL[@]}"
    echo "gear paused · $(pwr)"
    ;;
  resume)
    systemctl --user start "$SC"               # before watchdog, avoid the race
    systemctl --user start "$WATCHDOG" "${REST[@]}"
    echo "gear resumed · $(pwr)"
    ;;
  status)
    for u in "${ALL[@]}"; do
      printf '  %-28s %s\n' "$u" "$(systemctl --user is-active "$u")"
    done
    echo "  $(pwr)"
    ;;
  autostart-off) systemctl --user disable "${ALL[@]}" ;;
  # enable-per-policy lives in ONE place; this also starts what should run.
  # (The old inline `enable ALL` was enabling parvagues-sc at login, against
  # its own on-demand policy — a login must not start SuperDirt.)
  autostart-on)  python3 "$DIR/tools/rig_units.py" --ensure --apply ;;
  *) echo "usage: parvagues-gear {pause|resume|status|autostart-off|autostart-on}" >&2; exit 2 ;;
esac
