#!/command/with-contenv bash

echo "Starting 5q12's Indexer Initialization (S6-Overlay)..."

# Set timezone if provided
if [ ! -z "$TZ" ]; then
    echo "Setting timezone to $TZ"
    ln -sf /usr/share/zoneinfo/$TZ /etc/localtime
    echo $TZ > /etc/timezone
fi

# Ensure mount point directories exist
mkdir -p /config
mkdir -p /files

# Ensure required config subdirectories exist
echo "Ensuring config subdirectories exist..."
mkdir -p /config/zip_cache
mkdir -p /config/index_cache
mkdir -p /config/icons
mkdir -p /config/favicon

# CRITICAL: Always force-refresh local_api directory on every startup
echo "Force-refreshing local_api directory (critical backend files)..."
rm -rf /config/local_api

if [ -d "/app/default-config/local_api" ]; then
    cp -r /app/default-config/local_api /config/
    echo "✓ local_api directory refreshed from defaults"
else
    mkdir -p /config/local_api/style
    echo "⚠ Created minimal local_api structure (default not found)"
fi

# CRITICAL: Always force-refresh php directory on every startup
echo "Force-refreshing php directory (critical PHP class files)..."
rm -rf /config/php

if [ -d "/app/default-config/php" ]; then
    cp -r /app/default-config/php /config/
    echo "✓ php directory refreshed from defaults"
else
    mkdir -p /config/php
    echo "⚠ Created minimal php structure (default not found)"
fi

# Function to merge JSON configs using PHP
merge_config_json() {
    local existing_config="$1"
    local default_config="$2"
    local output_config="$3"
    
    cat > /tmp/merge_config.php << 'MERGE_EOF'
<?php
$existing = json_decode(file_get_contents($argv[1]), true);
$default = json_decode(file_get_contents($argv[2]), true);

if (!$existing || !$default) {
    echo "Error: Could not parse JSON files\n";
    exit(1);
}

function merge_recursive($existing, $default) {
    $result = $existing;
    
    foreach ($default as $key => $value) {
        if (!array_key_exists($key, $result)) {
            $result[$key] = $value;
            echo "Added missing config field: $key\n";
        } elseif (is_array($value) && is_array($result[$key])) {
            $result[$key] = merge_recursive($result[$key], $value);
        }
    }
    
    return $result;
}

$merged = merge_recursive($existing, $default);

$existing_version = $existing['version'] ?? 'unknown';
$default_version = $default['version'] ?? 'unknown';

if ($existing_version !== $default_version) {
    echo "Updating version from $existing_version to $default_version\n";
    $merged['version'] = $default_version;
}

file_put_contents($argv[3], json_encode($merged, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
echo "Config merge completed successfully\n";
MERGE_EOF

    php /tmp/merge_config.php "$existing_config" "$default_config" "$output_config"
    local merge_result=$?
    rm -f /tmp/merge_config.php
    return $merge_result
}

# Handle config.json with version checking and field merging
echo "Checking config.json version and updating if needed..."

if [ -f "/app/default-config/config.json" ]; then
    if [ -f "/config/config.json" ]; then
        echo "Existing config.json found, checking for updates..."
        cp /config/config.json /config/config.json.backup
        
        if merge_config_json "/config/config.json" "/app/default-config/config.json" "/config/config.json.new"; then
            mv /config/config.json.new /config/config.json
            echo "✓ Config.json updated with missing fields and latest version"
        else
            echo "⚠ Config merge failed, keeping existing config.json"
            if [ -f "/config/config.json.backup" ]; then
                mv /config/config.json.backup /config/config.json
            fi
        fi
        rm -f /config/config.json.new /config/config.json.backup
    else
        echo "No existing config.json, copying default..."
        cp /app/default-config/config.json /config/config.json
        echo "✓ Default config.json copied"
    fi
else
    echo "⚠ No default config.json found"
    if [ ! -f "/config/config.json" ]; then
        echo "ERROR: No config.json found and no default available!"
        exit 1
    fi
fi

# Process environment variables and update config.json
echo "Processing environment variable overrides..."

if [ -f "/config/config.json" ]; then
    cat > /tmp/process_env_config.php << 'ENV_EOF'
<?php
$configFile = '/config/config.json';
$config = json_decode(file_get_contents($configFile), true);

if (!$config) {
    echo "Error: Could not parse config.json\n";
    exit(1);
}

$envMappings = [
    'INDEXER_ACCESS_URL' => ['main', 'access_url'],
    'INDEXER_CACHE_TYPE' => ['main', 'cache_type'], 
    'INDEXER_ICON_TYPE' => ['main', 'icon_type'],
    'INDEXER_DISABLE_FILE_DOWNLOADS' => ['main', 'disable_file_downloads'],
    'INDEXER_DISABLE_FOLDER_DOWNLOADS' => ['main', 'disable_folder_downloads'],
    'INDEXER_INDEX_HIDDEN' => ['main', 'index_hidden'],
    'INDEXER_INDEX_ALL' => ['main', 'index_all'],
    'INDEXER_DENY_LIST' => ['main', 'deny_list'],
    'INDEXER_ALLOW_LIST' => ['main', 'allow_list']
];

$changes = 0;

foreach ($envMappings as $envVar => $configPath) {
    $value = getenv($envVar);
    if ($value !== false) {
        $originalValue = $config[$configPath[0]][$configPath[1]] ?? null;
        
        if (in_array($envVar, ['INDEXER_DISABLE_FILE_DOWNLOADS', 'INDEXER_DISABLE_FOLDER_DOWNLOADS', 'INDEXER_INDEX_HIDDEN', 'INDEXER_INDEX_ALL'])) {
            $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
        }
        
        if ($originalValue !== $value) {
            $config[$configPath[0]][$configPath[1]] = $value;
            echo "Updated {$configPath[0]}.{$configPath[1]}: " . json_encode($originalValue) . " -> " . json_encode($value) . "\n";
            $changes++;
        }
    }
}

foreach ($_ENV as $envVar => $value) {
    if (preg_match('/^INDEXER_INDEX_FILETYPE_([A-Z0-9_]+)$/', $envVar, $matches)) {
        $filetype = strtolower($matches[1]);
        $configKey = "index_$filetype";
        
        if (isset($config['exclusions'][$configKey])) {
            $boolValue = filter_var($value, FILTER_VALIDATE_BOOLEAN);
            $originalValue = $config['exclusions'][$configKey];
            
            if ($originalValue !== $boolValue) {
                $config['exclusions'][$configKey] = $boolValue;
                echo "Updated exclusions.$configKey: " . json_encode($originalValue) . " -> " . json_encode($boolValue) . "\n";
                $changes++;
            }
        }
    }
    
    if (preg_match('/^INDEXER_VIEW_FILETYPE_([A-Z0-9_]+)$/', $envVar, $matches)) {
        $filetype = strtolower($matches[1]);
        $configKey = "view_$filetype";
        
        if (isset($config['viewable_files'][$configKey])) {
            $boolValue = filter_var($value, FILTER_VALIDATE_BOOLEAN);
            $originalValue = $config['viewable_files'][$configKey];
            
            if ($originalValue !== $boolValue) {
                $config['viewable_files'][$configKey] = $boolValue;
                echo "Updated viewable_files.$configKey: " . json_encode($originalValue) . " -> " . json_encode($boolValue) . "\n";
                $changes++;
            }
        }
    }
}

if ($changes > 0) {
    $result = file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    if ($result === false) {
        echo "Error: Could not write updated config.json\n";
        exit(1);
    }
    echo "Applied $changes environment variable overrides to config.json\n";
} else {
    echo "No environment variable overrides found\n";
}
ENV_EOF

    php /tmp/process_env_config.php
    rm -f /tmp/process_env_config.php
    echo "Environment variable processing completed"
fi

# Handle other configuration files
if [ -d "/app/default-config" ]; then
    echo "Checking for other missing configuration files..."
    
    find /app/default-config -type f | while read -r src_file; do
        rel_path="${src_file#/app/default-config/}"
        dst_file="/config/$rel_path"
        
        case "$rel_path" in
            local_api/*|php/*|config.json)
                continue
                ;;
        esac
        
        if [ ! -f "$dst_file" ]; then
            echo "Copying missing file: $rel_path"
            mkdir -p "$(dirname "$dst_file")"
            cp "$src_file" "$dst_file"
        fi
    done
    
    echo "✓ Configuration files check completed"
fi

# Remove existing symlinks/directories and recreate
echo "Setting up symlinks..."
if [ -d "/www/indexer/.indexer_files" ] && [ ! -L "/www/indexer/.indexer_files" ]; then
    rm -rf /www/indexer/.indexer_files
fi
if [ -d "/www/indexer/files" ] && [ ! -L "/www/indexer/files" ]; then
    rm -rf /www/indexer/files
fi

if [ -L "/www/indexer/.indexer_files" ]; then
    rm /www/indexer/.indexer_files
fi
if [ -L "/www/indexer/files" ]; then
    rm /www/indexer/files
fi

ln -sf /config /www/indexer/.indexer_files
ln -sf /files /www/indexer/files

echo "Symlinks created:"
echo "  /www/indexer/.indexer_files -> /config"
echo "  /www/indexer/files -> /files"

# Set proper ownership
echo "Setting proper ownership..."
chown -R www-data:www-data /config
chown -R www-data:www-data /files
chown -R www-data:www-data /www/indexer

# Verify symlinks
echo "Verifying symlinks..."
if [ -L "/www/indexer/.indexer_files" ]; then
    echo "✓ .indexer_files symlink created successfully"
else
    echo "✗ Failed to create .indexer_files symlink"
    exit 1
fi

if [ -L "/www/indexer/files" ]; then
    echo "✓ files symlink created successfully"
else
    echo "✗ Failed to create files symlink"
    exit 1
fi

# Test configurations
echo "Testing nginx configuration..."
nginx -t
if [ $? -ne 0 ]; then
    echo "✗ Nginx configuration test failed!"
    exit 1
fi
echo "✓ Nginx configuration test passed"

echo "Testing PHP-FPM configuration..."
php-fpm -t
if [ $? -ne 0 ]; then
    echo "✗ PHP-FPM configuration test failed!"
    exit 1
fi
echo "✓ PHP-FPM configuration test passed"

# Display container information
echo ""
echo "5q12's Indexer Container Information:"
echo "====================================="
echo "Environment: Docker (S6-Overlay v3)"
echo "Index.php location: /www/indexer/index.php"
echo "Config directory: /config (mounted)"
echo "Files directory: /files (mounted)"
echo "Nginx port: 5012"
echo "Version: 1.1.19"
echo "Process Manager: S6-Overlay (Secure, No Supervisor)"
echo ""

echo "Configuration status:"
if [ -f "/config/config.json" ]; then
    if command -v php >/dev/null 2>&1; then
        current_version=$(php -r "
            \$config = json_decode(file_get_contents('/config/config.json'), true);
            echo isset(\$config['version']) ? \$config['version'] : 'unknown';
        " 2>/dev/null || echo "unknown")
        echo "  ✓ config.json: Present (version: $current_version)"
    else
        echo "  ✓ config.json: Present"
    fi
else
    echo "  ✗ config.json: Missing"
fi

[ -d "/config/local_api" ] && echo "  ✓ local_api: Refreshed" || echo "  ✗ local_api: Missing"
[ -d "/config/php" ] && echo "  ✓ php: Refreshed" || echo "  ✗ php: Missing"
[ -d "/config/zip_cache" ] && echo "  ✓ zip_cache: Ready"
[ -d "/config/index_cache" ] && echo "  ✓ index_cache: Ready"

echo ""
echo "Security enhancements:"
echo "  ✓ S6-Overlay process supervision (secure)"
echo "  ✓ No supervisor vulnerabilities"
echo "  ✓ Environment variable configuration support"
echo "  ✓ Enhanced configuration merging"
echo ""
echo "Services will start: nginx + php-fpm"
echo "Initialization complete - services starting..."
