#!/usr/bin/env bash
# Launch both NocoDB (backend) and React (frontend)

set -e

cleanup() {
  echo ""
  echo "Shutting down..."
  if [ -n "$REACT_PID" ]; then
    kill "$REACT_PID" 2>/dev/null
  fi
  docker stop nocodb 2>/dev/null
  echo "Done."
}

trap cleanup EXIT INT TERM

# Start NocoDB container
if docker ps --format '{{.Names}}' | grep -q '^nocodb$'; then
  echo "NocoDB already running on port 8090"
else
  echo "Starting NocoDB..."
  docker start nocodb 2>/dev/null || docker run -d \
    --name nocodb \
    -p 8090:8080 \
    nocodb/nocodb:latest
  echo "NocoDB started on port 8090"
fi

# Wait for NocoDB to be ready
echo "Waiting for NocoDB..."
for i in $(seq 1 30); do
  if curl -s http://localhost:8090/api/v1/health >/dev/null 2>&1; then
    echo "NocoDB is ready"
    break
  fi
  sleep 1
done

# Start React dev server
echo "Starting React dev server..."
cd "$(dirname "$0")"
npm start &
REACT_PID=$!

wait $REACT_PID
