#!/bin/bash
set -e

# Definir ruta del archivo .env
ENV_FILE="/var/www/html/.env"

# Siempre regenerar el archivo .env para asegurar que las variables de entorno (YAML) tengan prioridad
echo "Generating .env file from environment variables..."

# Vaciar/Crear archivo
: > "$ENV_FILE"

# Función helper para escribir variables
write_env() {
    local key=$1
    local val=$2
    if [ ! -z "$val" ]; then
        echo "$key=$val" >> "$ENV_FILE"
    fi
}

# Escribir variables críticas
# Base de Datos
write_env "DB_HOST" "${DB_HOST:-db}"
write_env "DB_NAME" "${DB_NAME:-contenedor_ibiza}"
write_env "DB_USER" "${DB_USER:-root}"
write_env "DB_PASS" "${DB_PASS:-password}"

# Aplicación
write_env "SITE_URL" "${SITE_URL:-http://localhost}"
write_env "TIMEZONE" "${TIMEZONE:-America/Mexico_City}"

# Sesión
write_env "SESSION_NAME" "${SESSION_NAME:-ibiza_session}"
write_env "SESSION_LIFETIME" "${SESSION_LIFETIME:-86400}"

# Telegram
write_env "TELEGRAM_BOT_TOKEN" "${TELEGRAM_BOT_TOKEN}"

echo ".env file generated successfully."

# Ajustar permisos por si acaso
chown www-data:www-data "$ENV_FILE"

# Ejecutar el comando original (CMD del Dockerfile)
exec "$@"
