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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PORT="${AUTOPROTOCOL_PORT:-8501}"
PID_FILE="$ROOT/.tmp/autoprotocol-webapp.pid"
TAILSCALE_IP="$(tailscale ip -4 2>/dev/null | head -n1 || true)"
LOCAL_URL="http://127.0.0.1:${PORT}/"
TAILNET_URL="${TAILSCALE_IP:+http://${TAILSCALE_IP}:${PORT}/}"
SERVICE_ACTIVE="no"

if systemctl --user is-active --quiet autoprotocol-webapp.service 2>/dev/null; then
  SERVICE_ACTIVE="yes"
  echo "OK service autoprotocol-webapp.service active"
fi

if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
  echo "OK process pid=$(cat "$PID_FILE")"
elif [[ "$SERVICE_ACTIVE" != "yes" ]]; then
  echo "FAIL process not running"
fi

if curl -fsS -o /dev/null -w 'OK local_http %{http_code} %{url_effective}\n' "$LOCAL_URL"; then
  :
else
  echo "FAIL local_http $LOCAL_URL"
fi

if [[ -n "$TAILNET_URL" ]]; then
  if curl -fsS -o /dev/null -w 'OK tailnet_http %{http_code} %{url_effective}\n' "$TAILNET_URL"; then
    :
  else
    echo "FAIL tailnet_http $TAILNET_URL"
  fi
  echo "URL $TAILNET_URL"
else
  echo "WARN tailscale ip not found"
fi
