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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUNTIME_DIR="$ROOT_DIR/.runtime"
PORT="${PORT:-8787}"
TOKEN="${HERMES_PUBLIC_TOKEN:-836c0381ed6a6a442e6e5a4aa35984ec}"
SERVER_PID_FILE="$RUNTIME_DIR/vinod-server.pid"
TUNNEL_PID_FILE="$RUNTIME_DIR/vinod-cloudflare.pid"
SERVER_LOG="$RUNTIME_DIR/vinod-server.log"
TUNNEL_LOG="$RUNTIME_DIR/vinod-cloudflare.log"
URL_FILE="$RUNTIME_DIR/vinod-cloudflare.url"

mkdir -p "$RUNTIME_DIR"
cd "$ROOT_DIR"

is_running() {
  local pid="${1:-}"
  [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null
}

pid_cwd() {
  local pid="${1:-}"
  [[ -n "$pid" ]] || return 1
  lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n 's/^n//p'
}

start_server() {
  local existing_pid
  existing_pid="$(lsof -tiTCP:"$PORT" -sTCP:LISTEN 2>/dev/null | head -n 1 || true)"
  if is_running "$existing_pid"; then
    local cwd
    cwd="$(pid_cwd "$existing_pid" || true)"
    if [[ "$cwd" == "$ROOT_DIR" ]]; then
      echo "$existing_pid" > "$SERVER_PID_FILE"
      return
    fi
    echo "Port $PORT is already used by PID $existing_pid outside Vinod: $cwd" >&2
    exit 1
  fi

  HERMES_PUBLIC_TOKEN="$TOKEN" PORT="$PORT" nohup node server.js > "$SERVER_LOG" 2>&1 &
  echo "$!" > "$SERVER_PID_FILE"

  for _ in {1..40}; do
    if curl -fsS -H "x-hermes-token: $TOKEN" "http://localhost:$PORT/api/health" >/dev/null 2>&1; then
      return
    fi
    sleep 0.25
  done

  echo "Vinod server did not become healthy. Log: $SERVER_LOG" >&2
  tail -n 60 "$SERVER_LOG" >&2 || true
  exit 1
}

stop_old_tunnel() {
  local pid
  pid="$(cat "$TUNNEL_PID_FILE" 2>/dev/null || true)"
  if is_running "$pid"; then
    kill "$pid" 2>/dev/null || true
  fi

  while IFS= read -r pid; do
    [[ -n "$pid" ]] || continue
    kill "$pid" 2>/dev/null || true
  done < <(pgrep -f "cloudflared tunnel --url http://localhost:$PORT" || true)
}

start_tunnel() {
  : > "$TUNNEL_LOG"
  rm -f "$URL_FILE"
  stop_old_tunnel

  cloudflared tunnel --url "http://localhost:$PORT" --protocol http2 --no-autoupdate > "$TUNNEL_LOG" 2>&1 &
  echo "$!" > "$TUNNEL_PID_FILE"

  for _ in {1..80}; do
    local url
    url="$(grep -Eo 'https://[-a-z0-9]+\.trycloudflare\.com' "$TUNNEL_LOG" | tail -n 1 || true)"
    if [[ -n "$url" ]] && grep -q "Registered tunnel connection" "$TUNNEL_LOG"; then
      printf '%s?token=%s\n' "$url" "$TOKEN" > "$URL_FILE"
      cat "$URL_FILE"
      return
    fi
    sleep 0.5
  done

  echo "Cloudflare tunnel did not return a URL. Log: $TUNNEL_LOG" >&2
  tail -n 80 "$TUNNEL_LOG" >&2 || true
  exit 1
}

start_server
start_tunnel
