#!/bin/sh
set -eu

ACTION="${1:-status}"
run_root() {
  if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi
}

case "$ACTION" in
  start|stop|restart)
    run_root systemctl "$ACTION" atonal-provider.service
    ;;
  status)
    systemctl status atonal-provider.service --no-pager
    ;;
  logs)
    exec journalctl -u atonal-provider.service -n 200 -f
    ;;
  console)
    URL="http://127.0.0.1:18181"
    if command -v xdg-open >/dev/null 2>&1; then exec xdg-open "$URL"; fi
    echo "$URL"
    ;;
  uninstall)
    if command -v dpkg >/dev/null 2>&1 && dpkg -s atonal-provider >/dev/null 2>&1; then
      run_root dpkg --remove atonal-provider
    elif command -v rpm >/dev/null 2>&1 && rpm -q atonal-provider >/dev/null 2>&1; then
      run_root rpm -e atonal-provider
    else
      echo "ATONAL Provider package is not installed" >&2
      exit 1
    fi
    echo "Identity data remains in /var/lib/atonal"
    ;;
  purge-data)
    printf "This permanently deletes the Provider identity. Type DELETE to continue: "
    read -r CONFIRMATION
    if [ "$CONFIRMATION" != "DELETE" ]; then echo "Cancelled"; exit 1; fi
    run_root systemctl stop atonal-provider.service 2>/dev/null || true
    run_root rm -rf /var/lib/atonal
    echo "ATONAL Provider identity data was removed"
    ;;
  *)
    echo "Usage: atonal-provider <start|stop|restart|status|logs|console|uninstall|purge-data>" >&2
    exit 2
    ;;
esac
