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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
pids=()

cleanup() {
  for pid in "${pids[@]:-}"; do
    if kill -0 "$pid" >/dev/null 2>&1; then
      kill -TERM "-$pid" >/dev/null 2>&1 || kill "$pid" >/dev/null 2>&1 || true
    fi
  done
  wait >/dev/null 2>&1 || true
}

trap cleanup EXIT INT TERM

start_group() {
  local name="$1"
  shift
  echo "Starting $name"
  setsid "$@" &
  pids+=("$!")
}

cd "$ROOT_DIR"
start_group "backend" npm run dev:backend
start_group "web" npm run dev:web

echo "Dev environment is running."
echo "Frontend: http://localhost:5173"
echo "Gateway:  http://localhost:3000"
echo "Press Ctrl+C to stop everything."

wait -n "${pids[@]}"
