#!/bin/sh

# Script to dynamically replace environment variables in the static files
# This allows updating env variables without rebuilding the container

# The directory where the static files are located
ROOT_DIR=/usr/share/nginx/html

# Check if .env file exists
if [ -f "$ROOT_DIR/.env" ]; then
  echo "Loading environment variables..."
  
  # Create env-config.js with the environment variables
  echo "window.env = {" > $ROOT_DIR/env-config.js
  
  # Extract variables starting with VITE_ and add them to env-config.js
  grep '^VITE_' $ROOT_DIR/.env | while read -r line; do
    # Split the line into variable name and value
    var_name=$(echo $line | cut -d '=' -f1)
    var_value=$(echo $line | cut -d '=' -f2-)
    
    # Remove VITE_ prefix for the frontend variable name
    frontend_var_name=$(echo $var_name | sed 's/^VITE_//')
    
    # Add the variable to env-config.js
    echo "  $frontend_var_name: \"$var_value\"," >> $ROOT_DIR/env-config.js
  done
  
  # Close the JavaScript object
  echo "};" >> $ROOT_DIR/env-config.js
  
  echo "Environment variables loaded successfully."
fi

# Execute the command passed to the script (usually start nginx)
exec "$@"
