#!/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.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0"
export SUPABASE_SERVICE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU"

# --- 等待 postgrest (通过 Kong proxy) 可访问 ---
echo "[kong] Waiting for PostgREST to be reachable via Kong..."
until curl -s http://localhost:3000/ >/dev/null; do
  echo "[kong] Still waiting for PostgREST..."
  sleep 1
done
echo "[kong] PostgREST is reachable. Starting Kong..."

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