#!/usr/bin/php
<?php
/**
 * Auto-recreate containers for sites with auto_recreate_on_update enabled
 * This script is triggered asynchronously after a Docker image is pulled
 * 
 * Usage: php auto-recreate-containers.php <image_name>
 */

// Check if running from CLI
if (php_sapi_name() !== 'cli') {
    die("This script must be run from the command line\n");
}

// Get image name from command line argument
if ($argc < 2) {
    die("Usage: php auto-recreate-containers.php <image_name>\n");
}

$image_name = $argv[1];

// Include configuration file first to define MySQL constants
require_once(__DIR__ . '/../web-files/configs/config.php');

// Include required libraries
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/docker-api.php');

try {
    $MySQLMgmt = new mysqlmgmt();
    $DockerAPI = new docker_api();
    
    // Create direct PDO connection (use 127.0.0.1 for host-based script)
    $dsn = "mysql:host=127.0.0.1;port=3306;dbname=whp;charset=utf8mb4";
    $db = new PDO($dsn, 'root', trim(MYSQL_PASS), [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    
    error_log("Auto-recreate: Starting for image $image_name");
    
    // Find all sites using this image with auto_recreate_on_update enabled
    $stmt = $db->prepare("
        SELECT 
            s.id as site_id,
            s.site_name,
            s.username,
            s.auto_recreate_on_update,
            ct.base_image,
            sd.fqdn as primary_domain
        FROM whp.sites s
        JOIN whp.container_types ct ON s.container_type_id = ct.id
        JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
        WHERE ct.base_image = ?
        AND s.auto_recreate_on_update = 1
    ");
    
    $stmt->execute([$image_name]);
    $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($sites)) {
        error_log("Auto-recreate: No sites found with auto_recreate_on_update enabled for image $image_name");
        exit(0);
    }
    
    error_log("Auto-recreate: Found " . count($sites) . " sites to recreate containers for");
    
    // Process each site
    foreach ($sites as $site) {
        error_log("Auto-recreate: Processing site {$site['site_name']} (ID: {$site['site_id']})");
        
        try {
            // Get all containers for this site
            $stmt = $db->prepare("
                SELECT container_id, container_number 
                FROM whp.site_containers 
                WHERE site_id = ?
                ORDER BY container_number
            ");
            $stmt->execute([$site['site_id']]);
            $containers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if (empty($containers)) {
                error_log("Auto-recreate: No containers found for site {$site['site_name']}");
                continue;
            }
            
            // Recreate each container
            foreach ($containers as $container) {
                error_log("Auto-recreate: Recreating container {$container['container_id']} for site {$site['site_name']}");
                
                try {
                    // Stop and remove the old container
                    $DockerAPI->stop_container($container['container_id']);
                    $DockerAPI->remove_container($container['container_id']);
                    
                    // Get full site details for recreation
                    $stmt = $db->prepare("
                        SELECT 
                            s.*,
                            sd.fqdn as primary_domain,
                            ct.base_image,
                            ct.startup_env,
                            ct.mount_options,
                            ct.listen_port
                        FROM whp.sites s
                        JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                        JOIN whp.container_types ct ON s.container_type_id = ct.id
                        WHERE s.id = ?
                    ");
                    $stmt->execute([$site['site_id']]);
                    $site_details = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    // Get user UID
                    $uid = trim(shell_exec("id -u " . escapeshellarg($site_details['username'])));
                    if (!is_numeric($uid)) {
                        error_log("Auto-recreate: Invalid user {$site_details['username']}");
                        continue;
                    }
                    
                    // Create new container with same configuration
                    $container_number = $container['container_number'];
                    $container_name = $site_details['primary_domain'] . '-' . str_pad($container_number, 2, '0', STR_PAD_LEFT);
                    
                    // Prepare environment variables
                    $env_vars = [
                        'WHP_USER=' . $site_details['username'],
                        'WHP_UID=' . $uid,
                        'WHP_DOMAIN=' . $site_details['primary_domain'],
                        'WHP_CONTAINER_NUMBER=' . $container_number
                    ];
                    
                    // Add user variables
                    if (!empty($site_details['user_variables'])) {
                        $user_vars = json_decode($site_details['user_variables'], true);
                        foreach ($user_vars as $var_name => $var_value) {
                            $env_vars[] = $var_name . '=' . $var_value;
                        }
                    }
                    
                    // Process startup environment variables
                    if (!empty($site_details['startup_env'])) {
                        $startup_env = json_decode($site_details['startup_env'], true);
                        if ($startup_env) {
                            foreach ($startup_env as $var_name => $var_value) {
                                // Replace dynamic variables
                                $var_value = $MySQLMgmt->replaceDynamicVariables(
                                    $var_value, 
                                    $site_details['username'], 
                                    $site_details['primary_domain'], 
                                    $uid, 
                                    $container_number, 
                                    $site_details['listen_port'] ?? 80
                                );
                                $env_vars[] = $var_name . '=' . $var_value;
                            }
                        }
                    }
                    
                    // Prepare volumes
                    $volumes = [
                        '/docker/users/' . $site_details['username'] . '/' . $site_details['primary_domain'] . ':/var/www/html'
                    ];
                    
                    // Process mount options
                    if (!empty($site_details['mount_options'])) {
                        $mount_options = json_decode($site_details['mount_options'], true);
                        if ($mount_options && isset($mount_options['volumes'])) {
                            foreach ($mount_options['volumes'] as $volume) {
                                $source = $MySQLMgmt->replaceDynamicVariables(
                                    $volume['source'], 
                                    $site_details['username'], 
                                    $site_details['primary_domain'], 
                                    $uid, 
                                    $container_number, 
                                    $site_details['listen_port'] ?? 80
                                );
                                $target = $MySQLMgmt->replaceDynamicVariables(
                                    $volume['target'], 
                                    $site_details['username'], 
                                    $site_details['primary_domain'], 
                                    $uid, 
                                    $container_number, 
                                    $site_details['listen_port'] ?? 80
                                );
                                $volumes[] = $source . ':' . $target;
                            }
                        }
                    }
                    
                    // Create new container config
                    $container_config = [
                        'image' => $site_details['base_image'],
                        'name' => $container_name,
                        'labels' => [
                            'whp.user' => $site_details['username'],
                            'whp.domain' => $site_details['primary_domain'],
                            'whp.site_id' => strval($site['site_id']),
                            'whp.container_number' => strval($container_number)
                        ],
                        'env' => $env_vars,
                        'volumes' => $volumes,
                        'cpu' => $site_details['cpu_per_container'],
                        'memory' => $site_details['memory_per_container'],
                        'network' => 'client-net'
                    ];
                    
                    $result = $DockerAPI->create_container($container_config);
                    
                    if ($result['success']) {
                        // Update container info in database
                        $stmt = $db->prepare("UPDATE whp.site_containers SET container_id = ?, status = 'running' WHERE site_id = ? AND container_number = ?");
                        $stmt->execute([$result['container_id'], $site['site_id'], $container_number]);
                        
                        error_log("Auto-recreate: Successfully recreated container {$container_name} with ID {$result['container_id']}");
                    } else {
                        error_log("Auto-recreate: Failed to create new container {$container_name}: " . $result['error']);
                    }
                    
                } catch (Exception $e) {
                    error_log("Auto-recreate: Error recreating container {$container['container_id']}: " . $e->getMessage());
                }
                
                // Add a small delay between container recreations to avoid overwhelming the system
                sleep(2);
            }
            
            // After all containers are recreated, reconfigure HAProxy
            try {
                require_once('/docker/whp/web/libs/haproxy_manager.php');
                $haproxy_manager = new haproxy_manager();
                $haproxy_result = $haproxy_manager->configureSite($site['site_id'], $site_details ?? $site);
                
                if ($haproxy_result['success']) {
                    error_log("Auto-recreate: HAProxy reconfigured for site {$site['site_name']}");
                } else {
                    error_log("Auto-recreate: Failed to reconfigure HAProxy for site {$site['site_name']}: " . $haproxy_result['error']);
                }
            } catch (Exception $e) {
                error_log("Auto-recreate: Error reconfiguring HAProxy for site {$site['site_name']}: " . $e->getMessage());
            }
            
        } catch (Exception $e) {
            error_log("Auto-recreate: Error processing site {$site['site_name']}: " . $e->getMessage());
        }
    }
    
    error_log("Auto-recreate: Completed processing for image $image_name");
    
} catch (Exception $e) {
    error_log("Auto-recreate: Fatal error: " . $e->getMessage());
    exit(1);
}