#!/usr/bin/env bash
# FleetTruck360 — local development helper.
#   scripts/dev.sh start    start database (private MariaDB :3307), API :8010, dashboard :5174, website :4321, queue + scheduler
#   scripts/dev.sh stop     stop everything started by this script
#   scripts/dev.sh status   show what is running
#   scripts/dev.sh reset    rebuild the database with demo data (php artisan migrate:fresh --seed)
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DATA="${FLEET_TMS_DATA:-$HOME/.local/share/fleet-tms}"
RUN="$DATA/run"; LOG="$DATA/log"
mkdir -p "$RUN" "$LOG"

is_up() { [ -f "$RUN/$1.pid" ] && kill -0 "$(cat "$RUN/$1.pid")" 2>/dev/null; }

start_bg() { # name, dir, command...
  local name=$1 dir=$2; shift 2
  if is_up "$name"; then echo "  $name already running"; return; fi
  (cd "$dir" && nohup "$@" >"$LOG/$name.log" 2>&1 & echo $! >"$RUN/$name.pid")
  echo "  started $name (log: $LOG/$name.log)"
}

start_db() {
  if [ -S "$RUN/mysqld.sock" ] && /opt/lampp/bin/mysqladmin --defaults-file="$DATA/my.cnf" -uroot -p"$(cat "$DATA/root-password.txt" 2>/dev/null)" ping >/dev/null 2>&1; then
    echo "  database already running"; return
  fi
  if [ ! -f "$DATA/my.cnf" ]; then echo "  no private database at $DATA (using DB settings from backend/.env)"; return; fi
  nohup /opt/lampp/sbin/mysqld --defaults-file="$DATA/my.cnf" --user="$(whoami)" >"$LOG/mysqld.out" 2>&1 &
  for _ in $(seq 1 20); do [ -S "$RUN/mysqld.sock" ] && break; sleep 1; done
  echo "  database started (127.0.0.1:3307)"
}

case "${1:-}" in
  start)
    echo "Starting FleetTruck360…"
    start_db
    start_bg api      "$ROOT/backend"  php artisan serve --host=127.0.0.1 --port=8010
    start_bg queue    "$ROOT/backend"  php artisan queue:work --tries=3
    start_bg schedule "$ROOT/backend"  php artisan schedule:work
    start_bg frontend "$ROOT/frontend" npx vite --host 127.0.0.1 --port 5174 --strictPort
    start_bg website  "$ROOT/website"  npx astro dev --host 127.0.0.1 --port 4321
    echo
    echo "  Website    http://localhost:4321"
    echo "  Dashboard  http://localhost:5174"
    echo "  API        http://localhost:8010/api/v1"
    ;;
  stop)
    for n in website frontend schedule queue api; do
      if is_up "$n"; then kill "$(cat "$RUN/$n.pid")" 2>/dev/null || true; echo "  stopped $n"; fi
      rm -f "$RUN/$n.pid"
    done
    if [ -f "$RUN/mysqld.pid" ]; then kill "$(cat "$RUN/mysqld.pid")" 2>/dev/null && echo "  stopped database" || true; fi
    ;;
  status)
    for n in api queue schedule frontend website; do printf "  %-9s %s\n" "$n" "$(is_up $n && echo running || echo stopped)"; done
    printf "  %-9s %s\n" database "$([ -S "$RUN/mysqld.sock" ] && echo running || echo stopped)"
    ;;
  reset)
    (cd "$ROOT/backend" && php artisan migrate:fresh --seed --force)
    ;;
  *) echo "usage: $0 start|stop|status|reset"; exit 1 ;;
esac
