#!/usr/bin/env bash
set -euo pipefail

SERVICE_NAME="openclaw-gateway.service"
RUN_AS_USER="isthekid"
GATEWAY_STATUS_CMD="openclaw gateway status"
AUDIT_LOG="/var/log/mr-anderson-recovery.log"
JOURNAL_LINES="150"

log_audit() {
  local verb="$1"
  local result="$2"
  printf '%s user=%s verb=%s result=%s\n' "$(date -Is)" "${SUDO_USER:-unknown}" "$verb" "$result" >> "$AUDIT_LOG"
}

run_as_owner() {
  sudo -u "$RUN_AS_USER" bash -lc "$*"
}

status_cmd() {
  echo "== systemd user service =="
  run_as_owner "systemctl --user status ${SERVICE_NAME} --no-pager || systemctl --user show ${SERVICE_NAME} --no-pager"
  echo
  echo "== service active state =="
  run_as_owner "systemctl --user is-active ${SERVICE_NAME}"
  echo
  echo "== gateway status =="
  run_as_owner "$GATEWAY_STATUS_CMD"
}

logs_cmd() {
  echo "== recent gateway journal =="
  run_as_owner "journalctl --user -u ${SERVICE_NAME} -n ${JOURNAL_LINES} --no-pager"
}

restart_cmd() {
  echo "== restarting ${SERVICE_NAME} =="
  run_as_owner "systemctl --user restart ${SERVICE_NAME}"
  sleep 3
  echo
  echo "== post-restart active state =="
  run_as_owner "systemctl --user is-active ${SERVICE_NAME}"
  echo
  echo "== post-restart gateway status =="
  run_as_owner "$GATEWAY_STATUS_CMD"
}

verify_cmd() {
  local active
  active="$(run_as_owner "systemctl --user is-active ${SERVICE_NAME}")"
  echo "service_state=${active}"
  if [[ "$active" != "active" ]]; then
    return 1
  fi
  run_as_owner "$GATEWAY_STATUS_CMD"
}

main() {
  local verb="${1:-}"
  if [[ $# -ne 1 ]]; then
    echo "usage: $0 <status|logs|restart|verify>" >&2
    exit 2
  fi

  case "$verb" in
    status)
      status_cmd
      log_audit "$verb" "success"
      ;;
    logs)
      logs_cmd
      log_audit "$verb" "success"
      ;;
    restart)
      restart_cmd
      log_audit "$verb" "success"
      ;;
    verify)
      verify_cmd
      log_audit "$verb" "success"
      ;;
    *)
      log_audit "$verb" "rejected"
      echo "unsupported verb" >&2
      exit 2
      ;;
  esac
}

main "$@"
