#!/bin/sh

echo "Starting 5q12's Indexer..."

# 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

# Initialize config directory with defaults if it's empty or missing key files
config_file_count=$(find /config -maxdepth 1 -type f | wc -l)
config_dir_count=$(find /config -maxdepth 1 -type d ! -name "." ! -name ".." | wc -l)

# Check if config.json exists (key indicator that config is properly initialized)
if [ ! -f "/config/config.json" ] || [ $config_file_count -eq 0 ]; then
    echo "Config directory is empty or missing key files, copying default configuration..."
    if [ -d "/app/default-config" ]; then
        # Use cp -a to preserve permissions and copy all content including hidden files
        cp -a /app/default-config/. /config/
        echo "Default configuration copied to /config/"
    else
        echo "Warning: No default config found, creating minimal structure..."
        # Create necessary subdirectories
        mkdir -p /config/zip_cache
        mkdir -p /config/index_cache
        mkdir -p /config/icons
        mkdir -p /config/favicon
        mkdir -p /config/local_api/style
        
        # Create minimal config.json if it doesn't exist
        if [ ! -f "/config/config.json" ]; then
            echo "Creating minimal config.json..."
            cat > /config/config.json << 'EOF'
{
    "version": "1.1.17",
    "main": {
        "access_url": "",
        "cache_type": "sqlite",
        "icon_type": "default",
        "disable_file_downloads": false,
        "disable_folder_downloads": false,
        "index_hidden": false,
        "index_all": false,
        "deny_list": "",
        "allow_list": ""
    },
    "exclusions": {
        "index_non-descript-files": true,
        "index_folders": true
    },
    "viewable_files": {
        "view_non-descript-files": false
    }
}
EOF
        fi
    fi
fi

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

# Remove existing symlinks/directories if they exist and aren't symlinks
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

# Remove existing symlinks to recreate them
if [ -L "/www/indexer/.indexer_files" ]; then
    rm /www/indexer/.indexer_files
fi
if [ -L "/www/indexer/files" ]; then
    rm /www/indexer/files
fi

# Create symlinks
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 for all directories
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 nginx configuration
echo "Testing nginx configuration..."
nginx -t

if [ $? -ne 0 ]; then
    echo "✗ Nginx configuration test failed!"
    exit 1
fi

echo "✓ Configuration test passed."

# Test PHP-FPM configuration
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"
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.17"
echo ""
echo "Volume mounts should be:"
echo "  -v /host/config:/config"
echo "  -v /host/files:/files"
echo ""
echo "Starting services..."

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