#!/usr/bin/env bash
# Start MongoDB, the API, and Apache, then check /api/health.

set -u

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

if [[ "$(id -u)" -eq 0 ]]; then
  SUDO=""
else
  SUDO="sudo"
fi

fail() {
  echo "Error: $1" >&2
  exit 1
}

echo "Starting Docker..."
docker compose up -d --build || fail "Docker did not start. See the output above."

echo "Reloading Apache..."
$SUDO a2enmod proxy proxy_http proxy_wstunnel rewrite ssl headers >/dev/null
$SUDO cp "$ROOT/deploy/meet.mystudyplanner.in.conf" /etc/apache2/sites-available/meet.mystudyplanner.in.conf
$SUDO cp "$ROOT/deploy/meet.mystudyplanner.in-le-ssl.conf" /etc/apache2/sites-available/meet.mystudyplanner.in-le-ssl.conf
$SUDO a2ensite meet.mystudyplanner.in.conf meet.mystudyplanner.in-le-ssl.conf >/dev/null
$SUDO apache2ctl configtest || fail "Apache configuration is invalid."
$SUDO systemctl reload apache2 || fail "Apache did not reload."

if [[ ! -f "$ROOT/client/dist/index.html" ]]; then
  fail "The website build is missing. Run: cd $ROOT/client && npm install --legacy-peer-deps && npm run build"
fi

echo "Checking API health..."
body=""
for _ in $(seq 1 30); do
  body="$(curl -fsS http://127.0.0.1:4000/api/health 2>/dev/null || true)"
  if [[ "$body" == *'"ok":true'* ]]; then
    break
  fi
  sleep 2
done

if [[ "$body" != *'"ok":true'* ]]; then
  echo "Error: API health check failed at http://127.0.0.1:4000/api/health" >&2
  docker compose logs --tail 40 server >&2 || true
  exit 1
fi

public="$(curl -fsS https://meet.mystudyplanner.in/api/health 2>/dev/null || true)"
if [[ "$public" != *'"ok":true'* ]]; then
  fail "Apache is up, but https://meet.mystudyplanner.in/api/health did not return ok."
fi

echo "Success: https://meet.mystudyplanner.in is up and the API health check passed."
exit 0
