#!/bin/sh
# Dream Server Dashboard Entrypoint
# Configures nginx with API key injection at runtime
#
# B1 fix: Reads API key from /data/dashboard-api-key.txt if DASHBOARD_API_KEY env is empty.
# This file is generated by dashboard-api on first start.

set -e

NGINX_CONF="/etc/nginx/conf.d/default.conf"
API_KEY="${DASHBOARD_API_KEY:-}"
KEY_FILE="/data/dashboard-api-key.txt"

# If no env var, try to read from file (generated by dashboard-api)
if [ -z "$API_KEY" ] && [ -f "$KEY_FILE" ]; then
    API_KEY=$(cat "$KEY_FILE" 2>/dev/null || echo "")
    if [ -n "$API_KEY" ]; then
        echo "[dashboard] Read API key from $KEY_FILE"
    fi
fi

# If API key is available, ensure nginx config has the auth header
# The template already includes the header with ${DASHBOARD_API_KEY} placeholder
# We need to substitute it with the actual value
if [ -n "$API_KEY" ]; then
    echo "[dashboard] Configuring nginx with API key auth injection"
    # Escape sed special characters in the API key to prevent injection
    ESCAPED_KEY=$(printf '%s\n' "$API_KEY" | sed 's/[&/\]/\\&/g')
    # Replace the placeholder (envsubst already ran, but may have left empty value)
    sed -i "s|Bearer \${DASHBOARD_API_KEY}|Bearer ${ESCAPED_KEY}|g" "$NGINX_CONF"
    sed -i "s|Bearer \"\"|Bearer \"${ESCAPED_KEY}\"|g" "$NGINX_CONF"
else
    echo "[dashboard] WARNING: No DASHBOARD_API_KEY found in env or $KEY_FILE"
    echo "[dashboard] API calls will fail with 401 until key is configured"
fi

# Start nginx
exec nginx -g 'daemon off;'
