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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUNTIME_DIR="$ROOT_DIR/.runtime"
PORT="${PORT:-8787}"

stop_pid_file() {
  local file="$1"
  local pid
  pid="$(cat "$file" 2>/dev/null || true)"
  if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
    kill "$pid" 2>/dev/null || true
  fi
  rm -f "$file"
}

stop_pid_file "$RUNTIME_DIR/vinod-cloudflare.pid"
stop_pid_file "$RUNTIME_DIR/vinod-server.pid"

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)

echo "Stopped Vinod processes recorded under $RUNTIME_DIR."
