#!/usr/bin/env php
<?php
/**
 * System Service SSL Certificate Refresh Script
 *
 * This script refreshes SSL certificates for system services (httpd, proftpd)
 * by requesting renewed certificates from HAProxy and restarting the services.
 *
 * This should be run via cron daily to ensure system services always have
 * up-to-date SSL certificates from HAProxy's automatic renewal process.
 *
 * Recommended cron schedule: Daily at 3 AM
 * 0 3 * * * /usr/bin/php /root/whp/scripts/refresh-system-ssl.php >/dev/null 2>&1
 */

// Determine the correct base directory
// In production: /docker/whp/web (synced from /root/whp/web-files)
// In development: /home/jknapp/code/whp/web-files
if (file_exists('/docker/whp/web/configs/config.php')) {
    // Production environment - web files are synced to /docker/whp/web/
    $webDir = '/docker/whp/web';
} else {
    // Development/testing environment - web files are in repo
    $webDir = dirname(__DIR__) . '/web-files';
}

// Validate web directory exists and contains required files
if (!is_dir($webDir)) {
    die("Error: Web directory not found: $webDir\n");
}

// Set error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Validate and include necessary files
$requiredFiles = [
    'configs/config.php',
    'libs/mysqlmgmt.php',
    'libs/ssl_manager.php'
];

foreach ($requiredFiles as $file) {
    $fullPath = $webDir . '/' . $file;

    // Security validation
    $realPath = realpath($fullPath);
    if ($realPath === false) {
        die("Error: Required file not found: $fullPath\n");
    }

    // Check for symlinks (security)
    if (is_link($fullPath)) {
        die("Security error: Symlink detected: $fullPath\n");
    }

    // Verify real path is within expected directory
    $expectedPrefix = realpath($webDir);
    if (strpos($realPath, $expectedPrefix . '/') !== 0) {
        die("Security error: File outside expected directory: $fullPath\n");
    }

    require_once($realPath);
}

echo "Starting system service SSL certificate refresh at " . date('Y-m-d H:i:s') . "\n";

try {
    // Initialize SSL Manager
    $ssl_manager = new ssl_manager();

    // Refresh all system service SSL certificates
    $results = $ssl_manager->refreshAllSystemServiceSSL();

    echo "Refresh completed at " . date('Y-m-d H:i:s') . "\n";
    echo "Total certificates: " . $results['total'] . "\n";
    echo "Refreshed: " . $results['refreshed'] . "\n";
    echo "Failed: " . $results['failed'] . "\n";

    if (!empty($results['errors'])) {
        echo "\nErrors encountered:\n";
        foreach ($results['errors'] as $error) {
            echo "  - " . $error . "\n";
        }
        exit(1); // Exit with error code if any failures occurred
    }

    echo "\nAll system service SSL certificates refreshed successfully.\n";
    exit(0);

} catch (Exception $e) {
    echo "Fatal error: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}
