#!/usr/bin/env sh
# Manage the existing Vibix Agent background service; does not re-pair or change policy.
set -eu
command=${1:-status}
case "$command" in
  start|stop|restart|status|logs|open) ;;
  *) printf '%s\n' 'Usage: vibix-control {open|start|stop|restart|status|logs}' >&2; exit 2 ;;
esac
if [ "$command" = open ]; then
  printf '%s\n' 'Vibix Commander: https://vibixmcp.etsyneuroclub.com/account'
  exit 0
fi
case "$(uname -s)" in
  Linux)
    command -v systemctl >/dev/null 2>&1 || { echo 'systemctl is required.' >&2; exit 1; }
    if [ "$(id -u)" -eq 0 ]; then
      if [ "$command" = logs ]; then exec journalctl -u vibix-agent.service -n 80 --no-pager; fi
      exec systemctl "$command" vibix-agent.service
    fi
    if [ "$command" = logs ]; then exec journalctl --user -u vibix-agent.service -n 80 --no-pager; fi
    exec systemctl --user "$command" vibix-agent.service
    ;;
  Darwin)
    uid=$(id -u)
    service="gui/$uid/com.vibix.commander.agent"
    domain="gui/$uid"
    path="$HOME/Library/LaunchAgents/com.vibix.commander.agent.plist"
    case "$command" in
      status)
        if launchctl print "$service" 2>/dev/null | grep -q 'state = running'; then
          echo 'Vibix Agent: running'
        else
          echo 'Vibix Agent: stopped'
          exit 3
        fi
        ;;
      logs) exec tail -n 80 "$HOME/.vibix-commander/pairing.log" ;;
      stop)
        launchctl bootout "$domain" "$path" 2>/dev/null || :
        exec launchctl disable "$service"
        ;;
      start)
        [ -f "$path" ] || { echo 'Pair your Mac using Vibix Commander Setup first.' >&2; exit 1; }
        launchctl enable "$service"
        launchctl bootstrap "$domain" "$path" 2>/dev/null || :
        exec launchctl kickstart -k "$service"
        ;;
      restart) "$0" stop && exec "$0" start ;;
    esac
    ;;
  *) echo 'Unsupported operating system.' >&2; exit 1 ;;
esac
