#!/bin/bash
# Quillio control script. Run it on your Mac, in Terminal, as the protected user.
#   quillio status | url | set-pin | restart | test-quiz | logs
HERE="$(cd "$(dirname "$0")" && pwd)"
# shellcheck disable=SC1091
. "$HERE/../config.env"

export ACADEMIC_HUB_DATA="$AH_DATA" ACADEMIC_HUB_LOGS="$AH_LOGS" ACADEMIC_HUB_PORT="$AH_PORT"
export PYTHONPATH="$AH_HOME/app"
PY="$AH_HOME/venv/bin/python"
DOMAIN="gui/$(id -u)"

case "${1:-help}" in
  status)
    for s in monitor dashboard; do
      if launchctl print "$DOMAIN/com.academichub.$s" >/dev/null 2>&1; then
        echo "$s: loaded"
      else
        echo "$s: NOT loaded"
      fi
    done
    "$PY" -m academic_hub.cli status
    ;;
  url)       echo "http://127.0.0.1:$AH_PORT" ;;
  set-pin)   "$PY" -m academic_hub.cli set-pin ;;
  restart)
    for s in monitor dashboard; do
      launchctl kickstart -k "$DOMAIN/com.academichub.$s" && echo "restarted $s"
    done
    ;;
  test-quiz) "$PY" -m academic_hub.quiz_ui --windowed ;;
  logs)      tail -n 40 "$AH_LOGS/monitor.log" "$AH_LOGS/dashboard.log" "$AH_LOGS/quiz.log" 2>/dev/null ;;
  *)
    echo "Usage: quillio status | url | set-pin | restart | test-quiz | logs"
    ;;
esac
