#!/usr/bin/env bash

set -euxo pipefail

# Set APISIX prefix to /app/code
PREFIX=/app/code

# Log file for APISIX output
LOG_FILE="/app/data/apisix.log"

# Ensure /app/data/conf exists
mkdir -p /app/data/conf

# Generate APISIX configuration (config.yaml) to connect to Cloudron etcd
cat <<EOF > /app/data/conf/config.yaml
apisix:
  etcd:
    host:
      - "http://${CLOUDRON_ETCD_HOST}:${CLOUDRON_ETCD_PORT}"
    prefix: "/apisix"
    timeout: 30
deployment:
  admin:
    admin_key:
      - name: admin
        key: ${CLOUDRON_APP_SECRET}
        role: admin

# Other APISIX configuration can go here if needed

EOF

# Print generated config.yaml and environment variables for debugging
cat /app/data/conf/config.yaml >> "${LOG_FILE}" 2>&1
env >> "${LOG_FILE}" 2>&1

# Set APISIX_CONF_FILE environment variable
export APISIX_CONF_FILE=/app/data/conf/config.yaml

# Initialize APISIX
/app/code/bin/apisix init >> "${LOG_FILE}" 2>&1

# Initialize etcd connection for APISIX
/app/code/bin/apisix init_etcd >> "${LOG_FILE}" 2>&1

# Start OpenResty (APISIX server)
/usr/local/openresty/bin/openresty -p ${PREFIX} -g 'daemon off;' >> "${LOG_FILE}" 2>&1 &

# Tail the log file to keep the container running and show output
tail -f "${LOG_FILE}"