#!/bin/sh
set -eu
LABEL=com.getdasha.compute.provider
APP_DIR="$HOME/Library/Application Support/Dasha Compute"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"

[ -r "$APP_DIR/provider.env" ] || { echo "Dasha Compute is not installed." >&2; exit 1; }
. "$APP_DIR/provider.env"
run_agent() {
  unset DASHA_PROVIDER_KEY || true
  DASHA_PROVIDER_KEY= DASHA_COORDINATOR_URL=$DASHA_COORDINATOR_URL DASHA_PROVIDER_ID=$DASHA_PROVIDER_ID DASHA_MODEL_MAP=$DASHA_MODEL_MAP DASHA_BENCHMARK_PATH=$DASHA_BENCHMARK_PATH ${DASHA_PROVIDER_KEY_FILE:+DASHA_PROVIDER_KEY_FILE=$DASHA_PROVIDER_KEY_FILE} "$DASHA_PYTHON" "$APP_DIR/agent.py" "$@"
}

case "${1:-status}" in
  status)
    if launchctl print "gui/$(id -u)/$LABEL" >/dev/null 2>&1; then echo "Dasha Compute is running as $DASHA_PROVIDER_ID."; else echo "Dasha Compute is stopped."; exit 1; fi
    ;;
  doctor) run_agent --doctor ;;
  benchmark) run_agent --benchmark ;;
  logs) exec tail -n 100 -f "$HOME/Library/Logs/Dasha Compute/provider.log" "$HOME/Library/Logs/Dasha Compute/provider-error.log" ;;
  start) launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null || true; launchctl kickstart -k "gui/$(id -u)/$LABEL" ;;
  stop) launchctl bootout "gui/$(id -u)" "$PLIST" ;;
  restart) launchctl bootout "gui/$(id -u)" "$PLIST" >/dev/null 2>&1 || true; launchctl bootstrap "gui/$(id -u)" "$PLIST" ;;
  uninstall)
    launchctl bootout "gui/$(id -u)" "$PLIST" >/dev/null 2>&1 || true
    /usr/bin/security delete-generic-password -a "$DASHA_PROVIDER_ID" -s "$LABEL" >/dev/null 2>&1 || true
    rm -f "$PLIST" "$HOME/bin/dasha-compute"
    rm -rf "$APP_DIR"
    echo "Dasha Compute was removed; logs remain in ~/Library/Logs/Dasha Compute."
    ;;
  *) echo "usage: dasha-compute status|doctor|benchmark|logs|start|stop|restart|uninstall" >&2; exit 2 ;;
esac
