#!/bin/bash
# Browser DB UI without Docker (Adminer + PHP built-in server).
# Requires: brew install php
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TOOLS="$ROOT/tools"
ADMINER="$TOOLS/adminer.php"
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"

if ! command -v php >/dev/null 2>&1; then
  echo "PHP not found. Install with:  brew install php"
  exit 1
fi

mkdir -p "$TOOLS"
if [ ! -f "$ADMINER" ]; then
  echo "Downloading Adminer to tools/adminer.php ..."
  curl -fsSL -o "$ADMINER" "https://github.com/vrana/adminer/releases/download/v4.8.1/adminer-4.8.1-en.php"
fi

if nc -z 127.0.0.1 8080 2>/dev/null; then
  echo "Port 8080 is already in use — opening existing service."
  open -a "Google Chrome" "http://127.0.0.1:8080/adminer.php" 2>/dev/null || true
  exit 0
fi

echo "Starting Adminer at http://127.0.0.1:8080/adminer.php"
echo "Login → MySQL | Server: 127.0.0.1 | User: root | Password: (empty) | Database: transporter"
echo "Press Ctrl+C to stop the server."
cd "$TOOLS"
php -S 127.0.0.1:8080 &
PHPPID=$!
trap 'kill "$PHPPID" 2>/dev/null' EXIT INT TERM
for _ in $(seq 1 20); do
  nc -z 127.0.0.1 8080 2>/dev/null && break
  sleep 0.2
done
open -a "Google Chrome" "http://127.0.0.1:8080/adminer.php" 2>/dev/null || true
wait "$PHPPID"
