#!/bin/bash

set -e

# Cloudron etcd connection
ETCD_HOST=${CLOUDRON_ETCD_HOST:-127.0.0.1}
ETCD_PORT=${CLOUDRON_ETCD_PORT:-2379}

echo "Etcd host: $ETCD_HOST"
echo "Etcd port: $ETCD_PORT"

# Wait for etcd to be ready
echo "Waiting for etcd to be ready..."
MAX_WAIT=30
WAIT_TIME=0
while ! curl -f "http://${ETCD_HOST}:${ETCD_PORT}/health" 2>/dev/null; do
  if [ $WAIT_TIME -ge $MAX_WAIT ]; then
    echo "Timeout waiting for etcd"
    exit 1
  fi
  echo "Etcd is unavailable - sleeping ($WAIT_TIME/$MAX_WAIT)"
  sleep 2
  WAIT_TIME=$((WAIT_TIME+2))
done

echo "Etcd is ready!"

# Create APISIX configuration file
cat > /usr/local/apisix/conf/config.yaml << 'EOF'
deployment:
  role: traditional
  role_traditional:
    config_provider: etcd
  admin:
    port: 9180
    allow_admin:
      - 0.0.0.0/0
    admin_key:
      - ${ADMIN_KEY:-admin-key-secret-change-me}
    admin_api_version: v3
  etcd:
    host:
      - ${ETCD_HOST}
    port: ${ETCD_PORT}
    prefix: "/apisix"
    timeout: 30
  apisix:
    ssl:
      ssl_trusted_certificate: /etc/ssl/certs/ca-certificates.crt
      ssl_protocols: "TLSv1.2 TLSv1.3"
    node_listen: 9080
    enable_ipv6: false
    enable_admin_cors: true
    enable_http2: true
  nginx_config:
    error_log: "logs/error.log"
    error_log_level: "warn"
    worker_processes: auto
    worker_rlimit_nofile: 20480
    event_worker_processes: 2
    worker_shutdown_timeout: 240s
EOF

echo "APISIX configuration created at /usr/local/apisix/conf/config.yaml"
cat /usr/local/apisix/conf/config.yaml

# Start APISIX
echo "Starting APISIX..."
exec /usr/bin/apisix start
