#!/bin/sh
set -eu
data=/var/lib/agentinosaurus-station
allow_local() {
 sudo -u agentinosaurus-station /usr/lib/agentinosaurus-station/station -data "$data" -allow-local-models
 echo 'Local model setup allowed. Station now downloads LiquidAI d1 (about 2 GB) and tests it. Follow the progress in your workspace.'
}
# Asked once, while pairing: the owner is at this computer then.
ask_local() {
 [ -t 0 ] || return 0
 [ ! -e "$data/local-models/approved" ] || return 0
 [ ! -e "$data/local-models/asked" ] || return 0
 printf '\nSet up the local AI model on this computer? Station downloads LiquidAI d1 (about 2 GB) once and analyses camera frames here, so they never go to a cloud AI provider. Model licence: LFM Open License v1.0. [Y/n] '
 read -r answer || answer=n
 install -d -m 0700 -o agentinosaurus-station -g agentinosaurus-station "$data/local-models"
 install -m 0600 -o agentinosaurus-station -g agentinosaurus-station /dev/null "$data/local-models/asked"
 case "$answer" in
  [nN]*) echo 'Skipped. To allow it later, run: sudo agentinosaurus-station allow-local-model' ;;
  *) allow_local ;;
 esac
}
case "${1:-status}" in
 status) exec systemctl status agentinosaurus-station.service ;;
 start|stop|restart) exec systemctl "$1" agentinosaurus-station.service ;;
 logs) exec journalctl -u agentinosaurus-station.service -n 60 -f ;;
 pair)
  if [ "$(id -u)" != 0 ]; then exec sudo "$0" pair; fi
  echo 'Agentinosaurus Station — pairing'
  echo 'Waiting for a pairing code. If already paired, open your workspace instead.'
  python3 - <<'PY'
import json, pathlib, time
p = pathlib.Path('/var/lib/agentinosaurus-station/pairing.json')
for _ in range(30):
    if p.exists() and time.time() - p.stat().st_mtime < 300:
        try:
            data = json.loads(p.read_text())
            print('\nOpen in your browser:', data['url'])
            print('Pairing code:', data['code'])
            break
        except (ValueError, KeyError):
            pass
    time.sleep(1)
else:
    raise SystemExit('No active pairing code. Check Station status or logs.')
PY
  ask_local
  ;;
 allow-local-model)
  if [ "$(id -u)" != 0 ]; then exec sudo "$0" allow-local-model; fi
  allow_local
  ;;
 *) echo 'Usage: agentinosaurus-station [status|pair|allow-local-model|logs|start|stop|restart]' >&2; exit 2 ;;
esac
