#!/bin/bash
set -e

echo "🔐 Loading secrets..."

# Function to load secret from file if *_FILE env var is set
# This is a fallback for environments where Docker Secrets are not configured
# The Framework's DockerSecretsResolver handles *_FILE pattern automatically
load_secret_fallback() {
    local var_name="$1"
    local file_var="${var_name}_FILE"

    # Only load manually if *_FILE is set but Framework hasn't loaded it yet
    # (This is mainly for backward compatibility during migration)
    if [ -n "${!file_var}" ] && [ -f "${!file_var}" ] && [ -z "${!var_name}" ]; then
        export "$var_name"="$(cat "${!file_var}")"
        echo "✅ Loaded $var_name from ${!file_var} (fallback)"
    fi
}

# Load secrets as fallback (Framework handles *_FILE pattern automatically via DockerSecretsResolver)
# This is mainly for backward compatibility during migration
load_secret_fallback "DB_PASSWORD"
load_secret_fallback "REDIS_PASSWORD"
load_secret_fallback "APP_KEY"
load_secret_fallback "VAULT_ENCRYPTION_KEY"
load_secret_fallback "SHOPIFY_WEBHOOK_SECRET"
load_secret_fallback "RAPIDMAIL_PASSWORD"
load_secret_fallback "GIT_TOKEN"

echo "✅ Secrets loading completed (Framework handles *_FILE pattern automatically)"

# Git Clone/Pull functionality
if [ -n "$GIT_REPOSITORY_URL" ]; then
    echo ""
    echo "📥 Cloning/Pulling code from Git repository..."
    
    GIT_BRANCH="${GIT_BRANCH:-main}"
    GIT_TARGET_DIR="/var/www/html"
    
    # Setup Git credentials if provided
    if [ -n "$GIT_TOKEN" ]; then
        # Use token for HTTPS authentication
        GIT_URL_WITH_AUTH=$(echo "$GIT_REPOSITORY_URL" | sed "s|https://|https://${GIT_TOKEN}@|")
    elif [ -n "$GIT_USERNAME" ] && [ -n "$GIT_PASSWORD" ]; then
        GIT_URL_WITH_AUTH=$(echo "$GIT_REPOSITORY_URL" | sed "s|https://|https://${GIT_USERNAME}:${GIT_PASSWORD}@|")
    else
        GIT_URL_WITH_AUTH="$GIT_REPOSITORY_URL"
    fi
    
    # Clone or pull repository
    if [ ! -d "$GIT_TARGET_DIR/.git" ]; then
        echo "📥 Cloning repository from $GIT_REPOSITORY_URL (branch: $GIT_BRANCH)..."
        
        # Remove existing files if they exist (from image build)
        # But preserve storage directory if it's a volume mount
        if [ "$(ls -A $GIT_TARGET_DIR 2>/dev/null)" ]; then
            echo "🗑️  Cleaning existing files (preserving storage)..."
            find "$GIT_TARGET_DIR" -mindepth 1 -maxdepth 1 ! -name "storage" -exec rm -rf {} \; 2>/dev/null || true
        fi
        
        # Clone into temporary directory first, then move contents (preserving storage)
        TEMP_CLONE="${GIT_TARGET_DIR}.tmp"
        rm -rf "$TEMP_CLONE" 2>/dev/null || true
        if git clone --branch "$GIT_BRANCH" --depth 1 "$GIT_URL_WITH_AUTH" "$TEMP_CLONE"; then
            # Remove only files/dirs that are not storage (which might be a volume mount)
            find "$GIT_TARGET_DIR" -mindepth 1 -maxdepth 1 ! -name "storage" -exec rm -rf {} \; 2>/dev/null || true
            # Move contents from temp directory to target (preserving storage)
            find "$TEMP_CLONE" -mindepth 1 -maxdepth 1 ! -name "." ! -name ".." -exec mv {} "$GIT_TARGET_DIR/" \; 2>/dev/null || true
            rm -rf "$TEMP_CLONE" 2>/dev/null || true
            echo "✅ Repository cloned successfully"
        else
            echo "❌ Git clone failed. Falling back to image contents."
            rm -rf "$TEMP_CLONE" 2>/dev/null || true
        fi
    else
        echo "🔄 Pulling latest changes from $GIT_BRANCH..."
        cd "$GIT_TARGET_DIR"
        
        # Fetch and reset to latest
        git fetch origin "$GIT_BRANCH" || {
            echo "⚠️  Git fetch failed. Using existing code."
        }
        git reset --hard "origin/$GIT_BRANCH" || {
            echo "⚠️  Git reset failed. Using existing code."
        }
        git clean -fd || true
    fi
    
    # Install/update dependencies if composer.json exists
    if [ -f "$GIT_TARGET_DIR/composer.json" ]; then
        echo "📦 Installing/updating Composer dependencies..."
        cd "$GIT_TARGET_DIR"
        composer install --no-dev --optimize-autoloader --no-interaction --no-scripts || {
            echo "⚠️  Composer install failed. Continuing..."
        }
        
        # Run composer scripts if needed
        composer dump-autoload --optimize --classmap-authoritative || true
    fi
    
    echo "✅ Git sync completed"
else
    echo ""
    echo "ℹ️  GIT_REPOSITORY_URL not set, using code from image"
fi

echo ""
echo "📊 Environment variables:"
env | grep -E "DB_|APP_" | grep -Ev "(PASSWORD|KEY|SECRET)" || true

echo ""
echo "🛠️ Adjusting filesystem permissions..."
chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache 2>/dev/null || true
find /var/www/html/storage /var/www/html/bootstrap/cache -type d -exec chmod 775 {} \; 2>/dev/null || true
find /var/www/html/storage /var/www/html/bootstrap/cache -type f -exec chmod 664 {} \; 2>/dev/null || true

# Start PHP-FPM in background (inherits all environment variables)
echo ""
echo "🚀 Starting PHP-FPM..."
php-fpm &

# Wait for PHP-FPM to be ready
sleep 2

# Start nginx in foreground (inherits all environment variables)
echo "🚀 Starting nginx..."
exec nginx -g 'daemon off;'
