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

# --- Check prerequisites ---

if ! command -v docker &>/dev/null; then
  echo "Error: docker is not installed. Install Docker first: https://docs.docker.com/get-docker/"
  exit 1
fi

if ! docker compose version &>/dev/null; then
  echo "Error: docker compose is not available. Install the Docker Compose plugin: https://docs.docker.com/compose/install/"
  exit 1
fi

# --- Setup ---

cd "$(dirname "$0")"

if [ ! -f nitter.conf ]; then
  echo "Creating nitter.conf from template..."
  HMAC_KEY=$(openssl rand -hex 32)
  sed "s/CHANGE_ME_TO_RANDOM_STRING/${HMAC_KEY}/" nitter.conf.template > nitter.conf
  echo "Generated HMAC key and wrote nitter.conf"
fi

# --- Start containers ---

echo "Starting Nitter containers..."
docker compose up -d

# --- Wait for health ---

echo "Waiting for Nitter to become healthy..."
MAX_ATTEMPTS=15
ATTEMPT=0
until curl -sf http://localhost:8080 >/dev/null 2>&1; do
  ATTEMPT=$((ATTEMPT + 1))
  if [ "$ATTEMPT" -ge "$MAX_ATTEMPTS" ]; then
    echo "Error: Nitter did not become healthy within 30 seconds."
    echo "Check logs with: docker compose -f $(pwd)/docker-compose.yml logs"
    exit 1
  fi
  sleep 2
done

# --- Done ---

echo ""
echo "Nitter is running at http://localhost:8080"
echo ""
echo "Add to your gateway config (gateway.json or minion.yml):"
echo "  plugins:"
echo "    nitter:"
echo "      enabled: true"
echo '      instanceUrl: "http://localhost:8080"'
