#!/bin/sh
set -e

# Default domain if not set
export DOMAIN=${DOMAIN:-cmlite.org}

# Default embed proxy ports (configurable via .env for multi-instance deployments)
export NOCODB_EMBED_PORT=${NOCODB_EMBED_PORT:-8881}
export N8N_EMBED_PORT=${N8N_EMBED_PORT:-8882}
export GITEA_EMBED_PORT=${GITEA_EMBED_PORT:-8883}
export MAILHOG_EMBED_PORT=${MAILHOG_EMBED_PORT:-8884}
export MINI_QR_EMBED_PORT=${MINI_QR_EMBED_PORT:-8885}
export EXCALIDRAW_EMBED_PORT=${EXCALIDRAW_EMBED_PORT:-8886}
export HOMEPAGE_EMBED_PORT=${HOMEPAGE_EMBED_PORT:-8887}
export VAULTWARDEN_EMBED_PORT=${VAULTWARDEN_EMBED_PORT:-8890}
export ROCKETCHAT_EMBED_PORT=${ROCKETCHAT_EMBED_PORT:-8891}
export GANCIO_EMBED_PORT=${GANCIO_EMBED_PORT:-8892}
export JITSI_EMBED_PORT=${JITSI_EMBED_PORT:-8893}
export GRAFANA_EMBED_PORT=${GRAFANA_EMBED_PORT:-8894}
export ALERTMANAGER_EMBED_PORT=${ALERTMANAGER_EMBED_PORT:-8895}

echo "Configuring nginx for domain: $DOMAIN"

# List of environment variables to substitute in templates
# IMPORTANT: must be explicit to avoid replacing nginx variables like $host, $remote_addr
VARS='${DOMAIN}'
VARS="${VARS} \${NOCODB_EMBED_PORT} \${N8N_EMBED_PORT} \${GITEA_EMBED_PORT}"
VARS="${VARS} \${MAILHOG_EMBED_PORT} \${MINI_QR_EMBED_PORT} \${EXCALIDRAW_EMBED_PORT}"
VARS="${VARS} \${HOMEPAGE_EMBED_PORT} \${VAULTWARDEN_EMBED_PORT} \${ROCKETCHAT_EMBED_PORT}"
VARS="${VARS} \${GANCIO_EMBED_PORT} \${JITSI_EMBED_PORT} \${GRAFANA_EMBED_PORT}"
VARS="${VARS} \${ALERTMANAGER_EMBED_PORT}"

# Template nginx configuration files with environment variables
envsubst "$VARS" < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf
envsubst "$VARS" < /etc/nginx/conf.d/api.conf.template > /etc/nginx/conf.d/api.conf
envsubst "$VARS" < /etc/nginx/conf.d/services.conf.template > /etc/nginx/conf.d/services.conf

echo "Nginx configuration templated successfully"

# Test configuration
nginx -t

# Execute the original nginx entrypoint
exec /docker-entrypoint.sh "$@"
