#!/command/with-contenv bash

# Get verbosity level (0=minimal, 1=normal, 2=verbose)
VERBOSITY="${ALIASVAULT_VERBOSITY:-0}"

# Copy certificates to nginx directory (they were created during init)
mkdir -p /etc/nginx/ssl
cp /certificates/ssl/* /etc/nginx/ssl/ 2>/dev/null || true

# Create SSL configuration file
cat > /etc/nginx/ssl.conf << "SSLEOF"
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_session_timeout 1d;
ssl_session_cache shared:MozTLS:10m;
ssl_session_tickets off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
SSLEOF

# Configure nginx based on FORCE_HTTPS_REDIRECT environment variable
FORCE_HTTPS_REDIRECT=${FORCE_HTTPS_REDIRECT:-false}
if [[ "${FORCE_HTTPS_REDIRECT}" == "true" ]]; then
    echo "Configuring nginx with HTTPS-only (443) - redirects HTTP to HTTPS"
    cp /etc/nginx/nginx-443.conf /etc/nginx/nginx.conf
else
    echo "Configuring nginx with HTTP and HTTPS support (80+443)"
    cp /etc/nginx/nginx-80-443.conf /etc/nginx/nginx.conf
fi

echo "Starting Nginx reverse proxy..."

# Set nginx error log level based on verbosity
if [ "$VERBOSITY" -ge 2 ]; then
    # Verbose: info level
    exec nginx -g "daemon off; error_log /dev/stderr info;"
elif [ "$VERBOSITY" -ge 1 ]; then
    # Normal: warn level
    exec nginx -g "daemon off; error_log /dev/stderr warn;"
else
    # Minimal: error level only
    exec nginx -g "daemon off; error_log /dev/stderr error;"
fi