#!/bin/sh

#######################################
# PART 1: NGINX CONFIG TEMPLATE HANDLING
#######################################

# Get nginx config template if it exists
CONFIG_TEMPLATE="/etc/nginx/conf.d/default.conf.template"
CONFIG_FILE="/etc/nginx/conf.d/default.conf"

# If template exists, generate config
if [ -f "$CONFIG_TEMPLATE" ]; then
  echo "-----------------------------"
  echo "Generating nginx config using PORT: $PORT"
  
  # Replace the PORT variable in the template
  envsubst '$PORT' < "$CONFIG_TEMPLATE" > "$CONFIG_FILE"
  
  echo "Nginx configuration generated."
fi

#######################################
# PART 2: ENVIRONMENT VARIABLE HANDLING
#######################################

# Set debug mode based on NODE_ENV
if [ "$NODE_ENV" = "production" ]; then
  DEBUG_MODE=$RACLETTE_DEBUG_MODE ??  "false"
else
  DEBUG_MODE=$RACLETTE_DEBUG_MODE ?? "true"
fi

echo "-----------------------------"
echo "Processing environment variables..."

# Initialize the configs object
CONFIG_STRING="window.configs = { RACLETTE_DEBUG_MODE: '${DEBUG_MODE}'"

# Automatically add all RACLETTE_ prefixed environment variables
for VAR in $(env | grep ^RACLETTE_ | cut -d= -f1); do
  # Get the value of the variable
  VALUE=$(eval echo \$$VAR)
  # Escape single quotes in the value to prevent JavaScript syntax errors
  ESCAPED_VALUE=$(echo "$VALUE" | sed "s/'/\\\\'/g")
  # Append to config string
  CONFIG_STRING="$CONFIG_STRING, $VAR: '$ESCAPED_VALUE'"
done

# Close the config object
CONFIG_STRING="$CONFIG_STRING }"

echo "Injecting config: $CONFIG_STRING"

# Determine the correct index.html location
if [ -f /usr/share/nginx/html/index.html ]; then
  INDEX_PATH="/usr/share/nginx/html/index.html"
elif [ -f /app/dist/index.html ]; then
  # For vite preview mode
  INDEX_PATH="/app/dist/index.html"
else
  echo "Error: Could not find index.html"
  exit 1
fi

# Check if window.configs already exists in the HTML
if grep -q "window\.configs" "$INDEX_PATH"; then
  # Replace existing window.configs
  sed -i "s@window\.configs.*@${CONFIG_STRING}@" "$INDEX_PATH"
  echo "✅ Replaced existing environment config in $INDEX_PATH"
else
  # Add new script tag before </head>
  SCRIPT_TAG="<script>${CONFIG_STRING}</script>"
  sed -i "s@</head>@${SCRIPT_TAG}\n</head>@" "$INDEX_PATH"
  echo "✅ Added new environment config to $INDEX_PATH"
fi

echo "Environment variables successfully injected into $INDEX_PATH"

#######################################
# PART 3: DEPLOYMENT TRIGGER (Optional for production)
#######################################

# Only trigger deployment notification if API backend URL is provided
if [ -n "$RACLETTE_API_BASE_URL" ]; then
  echo "-----------------------------"
  echo "Triggering deployment notification..."
  
  API_SERVER_URL="${RACLETTE_API_BASE_URL}/core/system/deploy"
  echo "Call Deploy Endpoint: $API_SERVER_URL"
  
  # Call the deploy endpoint to notify backend (optional, non-blocking)
  curl -X GET -H 'Accept-Version: 1.0' "$API_SERVER_URL" || echo "Deploy notification failed (non-critical)"
  echo "Deployment notification completed."
  echo "-----------------------------"
fi

#######################################
# PART 4: START MAIN PROCESS
#######################################

echo "Starting main application process..."

# Execute the main command (nginx)
exec "$@"