#!/bin/bash
set -euo pipefail

# --- 信号处理 ---
cleanup() {
  echo "[kong] Caught termination signal, shutting down..."
  exit 0
}
trap cleanup SIGINT SIGTERM SIGQUIT

# --- 日志目录准备 ---
mkdir -p /usr/local/kong/logs
touch /usr/local/kong/logs/kong-error.log
chown kong:kong /usr/local/kong/logs/kong-error.log
chmod 644 /usr/local/kong/logs/kong-error.log

# --- 环境变量配置 ---
export KONG_DATABASE="off"
export KONG_PG_HOST="127.0.0.1"
export KONG_PG_PORT="5432"
export KONG_PG_USER="supabase_admin"
export KONG_PG_PASSWORD="postgres"
export KONG_PG_DATABASE="postgres"

export KONG_LOG_LEVEL="debug"
export KONG_PROXY_ACCESS_LOG="/usr/local/kong/logs/kong-access.log"
export KONG_ADMIN_ACCESS_LOG="/usr/local/kong/logs/kong-access.log"
export KONG_PROXY_ERROR_LOG="/usr/local/kong/logs/kong-error.log"
export KONG_ADMIN_ERROR_LOG="/usr/local/kong/logs/kong-error.log"
export KONG_PREFIX="/usr/local/kong"
export KONG_DECLARATIVE_CONFIG="/supabase/kong/kong.yml"
export SUPABASE_ANON_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlLWRlbW8iLCJleHAiOjIwNjI5MjU1NjUsImlhdCI6MTc0NzU2NTU2NX0.l08_BczmnaDNCur8AK0Z-X6MZOHNNRWh7ij5aN6sLgU"
export SUPABASE_SERVICE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaXNzIjoic3VwYWJhc2UtZGVtbyIsImV4cCI6MjA2MjkyNTU2NSwiaWF0IjoxNzQ3NTY1NTY1fQ.18Lxnd9JrkNyV9q38l_8oQB8pwtZK8JwpLwpH2b4JaA"

# --- 等待 postgrest (通过 Kong proxy) 可访问 ---
echo "[kong] Waiting for PostgREST on localhost:3000 (not via Kong)..."
until curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/ | grep -qE "^(200|401|403)$"; do
  echo "[kong] Still waiting for PostgREST..."
  sleep 2.5
done

echo "[kong] PostgREST is reachable. Now starting Kong on port 8000..."

# --- 启动 Kong（使用 docker-entrypoint.sh + docker-start 模式） ---
exec /supabase/kong/docker-entrypoint.sh kong docker-start
