#!/bin/bash

migrateAppsToNewNetwork()
{
    local old_subnet="$1"
    local new_subnet="$2"
    
    if [[ -z "$old_subnet" || -z "$new_subnet" ]]; then
        isError "Both old and new subnets required for network migration"
    fi
    
    isNotice "Starting network migration from $old_subnet to $new_subnet"
    isNotice "This will update all installed applications to use the new network."
    echo ""
    
    # Get list of installed apps
    local installed_apps=$(getInstalledApps)
    
    if [[ -z "$installed_apps" ]]; then
        isNotice "No installed applications found for migration"
    fi
    
    local apps_updated=0
    local apps_failed=0
    
    for app_name in $installed_apps; do
        echo ""
        isNotice "Processing $app_name..."
        
        # Get app's compose file path
        local compose_file="$containers_dir/$app_name/compose.yml"
        
        if [[ ! -f "$compose_file" ]]; then
            isNotice "  No compose file found for $app_name, skipping"
            continue
        fi
        
        # Backup original compose file
        cp "$compose_file" "$compose_file.backup.$(date +%s)"
        
        # Update network references in compose file
        if updateComposeFileNetwork "$compose_file" "$old_subnet" "$new_subnet"; then
            # Restart the app to apply changes
            isNotice "  Restarting $app_name to apply network changes..."
            
            if dockerCommandRun "cd $containers_dir/$app_name && docker compose down" && \
               dockerCommandRun "cd $containers_dir/$app_name && COMPOSE_PROGRESS=plain docker compose up --quiet-pull -d"; then
                isSuccessful "  $app_name successfully migrated to new network"
                ((apps_updated++))
            else
                isError "Failed to restart $app_name after network update"
                # Restore backup
                mv "$compose_file.backup.$(date +%s)" "$compose_file"
                ((apps_failed++))
            fi
        else
            isError "Failed to update compose file for $app_name"
            ((apps_failed++))
        fi
    done
    
    echo ""
    isSuccessful "Network migration completed:"
    isSuccessful "  Apps updated: $apps_updated"
    if [[ $apps_failed -gt 0 ]]; then
        isError "Apps failed: $apps_failed"
    fi
}
