#!/bin/bash
# sms-server — control the SMS Guard Server macOS app (the DMG).
# Usage: ./sms-server {start|stop|restart|status|url|log|ps|open}
# Override the app location with SMS_APP_DIR if you moved the .app.
set -u

APP_DIR="${SMS_APP_DIR:-/Applications/SMS Guard Server.app}"
LAUNCHER="$APP_DIR/Contents/Resources/launcher.sh"
DATA="$HOME/Library/Application Support/SMS Guard Server/data"
STATE="$DATA/state.json"

cmd="${1:-status}"
case "$cmd" in
  start)   bash "$LAUNCHER" start ;;
  stop)    bash "$LAUNCHER" stop ;;
  restart) bash "$LAUNCHER" stop >/dev/null 2>&1; sleep 1; bash "$LAUNCHER" start ;;
  status)
    echo "app:  $APP_DIR"
    if [ -f "$STATE" ]; then cat "$STATE"; echo; else echo "state: not started"; fi
    echo "procs:"
    pgrep -fl "SMSGuardServer|pgdata|redis-server.*6380" | sed 's/^/  /' | head -5
    curl -s -m 4 -o /dev/null -w "  server :8500 -> HTTP %{http_code}\n" http://127.0.0.1:8500/health 2>/dev/null || echo "  server :8500 -> down"
    ;;
  url)
    python3 -c "import json,os;d=json.load(open(os.path.expanduser('$STATE')));print(d.get('url',''))" 2>/dev/null || echo ""
    ;;
  log)   tail -n "${2:-40}" "$DATA/logs/server.log" 2>/dev/null ;;
  logall) tail -n "${2:-40}" "$DATA/logs/launcher.log" 2>/dev/null ;;
  ps)    pgrep -fl "SMSGuardServer|pgdata|redis-server.*6380" | head -6 ;;
  open)   open "$APP_DIR" ;;
  *)
    echo "usage: $0 {start|stop|restart|status|url|log [n]|logall [n]|ps|open}"
    exit 1
    ;;
esac
