<?php
/**
 * Secure Key Generation Script
 * Generates cryptographically secure keys for JWT and other security features
 * Run this script to generate new secure keys for production
 */

// Security: This script should only be run from command line
if (php_sapi_name() !== 'cli') {
    die("This script can only be run from command line.\n");
}

echo "=== Secure Key Generation for Bus Check-in API ===\n\n";

/**
 * Generate a cryptographically secure random key
 */
function generateSecureKey($length = 64, $format = 'hex') {
    $bytes = random_bytes($length / 2);
    return $format === 'hex' ? bin2hex($bytes) : base64_encode($bytes);
}

/**
 * Generate JWT Secret Key
 */
function generateJWTSecret() {
    echo "Generating JWT Secret Key...\n";
    $secret = generateSecureKey(64, 'hex'); // 256 bits
    echo "JWT_SECRET: $secret\n\n";

    // Create or update JWT config file
    $configFile = __DIR__ . '/../config/jwt_secure.php';
    $configDir = dirname($configFile);

    if (!is_dir($configDir)) {
        mkdir($configDir, 0750, true);
    }

    $configContent = "<?php\n";
    $configContent .= "/**\n";
    $configContent .= " * Secure JWT Configuration\n";
    $configContent .= " * Generated on: " . date('Y-m-d H:i:s') . "\n";
    $configContent .= " */\n\n";
    $configContent .= "return [\n";
    $configContent .= "    'JWT_SECRET' => '$secret',\n";
    $configContent .= "    'JWT_ALGORITHM' => 'HS256',\n";
    $configContent .= "    'JWT_EXPIRY' => 24 * 60 * 60, // 24 hours\n";
    $configContent .= "    'JWT_ISSUER' => 'bus_checkin_api',\n";
    $configContent .= "    'JWT_REFRESH_EXPIRY' => 30 * 24 * 60 * 60 // 30 days\n";
    $configContent .= "];\n";

    file_put_contents($configFile, $configContent);
    chmod($configFile, 0600); // Restrictive permissions

    echo "JWT configuration saved to: $configFile\n";
    echo "File permissions set to 600 (owner read/write only)\n\n";
}

/**
 * Generate Database Encryption Key (for future use)
 */
function generateDatabaseKey() {
    echo "Generating Database Encryption Key...\n";
    $key = generateSecureKey(32, 'hex'); // 128 bits for AES-128
    echo "DB_ENCRYPTION_KEY: $key\n\n";

    // You can extend this to save to database config if needed
    return $key;
}

/**
 * Generate API Key for external services
 */
function generateAPIKey() {
    echo "Generating API Key for external services...\n";
    $key = 'sk_' . generateSecureKey(32, 'hex');
    echo "API_KEY: $key\n\n";
    return $key;
}

/**
 * Generate Certificate Pin for SSL Pinning
 */
function generateCertificatePin() {
    echo "Generating Certificate Pin (SHA-256)...\n";
    $pin = generateSecureKey(32, 'hex');
    echo "CERTIFICATE_PIN_SHA256: $pin\n\n";
    return $pin;
}

/**
 * Generate all security keys
 */
function generateAllKeys() {
    echo "Generating all security keys...\n\n";

    generateJWTSecret();
    $dbKey = generateDatabaseKey();
    $apiKey = generateAPIKey();
    $certPin = generateCertificatePin();

    // Create environment file template
    $envTemplate = "# Environment Configuration Template\n";
    $envTemplate .= "# Copy this to your .env file and update values for production\n\n";
    $envTemplate .= "# Application Environment\n";
    $envTemplate .= "APP_ENV=production\n\n";
    $envTemplate .= "# Database Configuration\n";
    $envTemplate .= "DB_HOST=your_database_host\n";
    $envTemplate .= "DB_NAME=your_database_name\n";
    $envTemplate .= "DB_USER=your_database_user\n";
    $envTemplate .= "DB_PASS=your_database_password\n\n";
    $envTemplate .= "# JWT Configuration (generated)\n";
    $envTemplate .= "JWT_SECRET=" . generateSecureKey(64, 'hex') . "\n";
    $envTemplate .= "JWT_ALGORITHM=HS256\n";
    $envTemplate .= "JWT_EXPIRY=86400\n";
    $envTemplate .= "JWT_ISSUER=bus_checkin_api\n\n";
    $envTemplate .= "# Security Keys (generated - keep secret!)\n";
    $envTemplate .= "DB_ENCRYPTION_KEY=$dbKey\n";
    $envTemplate .= "API_KEY=$apiKey\n";
    $envTemplate .= "CERTIFICATE_PIN_SHA256=$certPin\n\n";
    $envTemplate .= "# Other settings\n";
    $envTemplate .= "LOG_LEVEL=WARNING\n";
    $envTemplate .= "ENABLE_SECURITY_HEADERS=true\n";

    $envFile = __DIR__ . '/../.env.example';
    file_put_contents($envFile, $envTemplate);

    echo "Environment template saved to: $envFile\n\n";

    // Security recommendations
    echo "=== SECURITY RECOMMENDATIONS ===\n";
    echo "1. Never commit generated keys to version control\n";
    echo "2. Use environment variables in production\n";
    echo "3. Rotate keys periodically (recommended: every 90 days)\n";
    echo "4. Store keys in secure key management systems (AWS KMS, HashiCorp Vault, etc.)\n";
    echo "5. Use different keys for development, staging, and production\n";
    echo "6. Monitor key usage and set up alerts for suspicious activities\n";
    echo "7. Implement proper backup and recovery procedures for keys\n\n";

    echo "=== NEXT STEPS ===\n";
    echo "1. Update your production environment with the generated keys\n";
    echo "2. Test the application with new keys\n";
    echo "3. Set up key rotation schedule\n";
    echo "4. Configure monitoring and alerting\n";
    echo "5. Document key management procedures\n\n";
}

// Main execution
if ($argc > 1) {
    $command = $argv[1];

    switch ($command) {
        case 'jwt':
            generateJWTSecret();
            break;
        case 'all':
            generateAllKeys();
            break;
        default:
            echo "Usage: php generate_secure_keys.php [jwt|all]\n";
            echo "  jwt  - Generate JWT secret key only\n";
            echo "  all  - Generate all security keys\n";
            break;
    }
} else {
    echo "Usage: php generate_secure_keys.php [jwt|all]\n\n";
    echo "Generating JWT secret key by default...\n\n";
    generateJWTSecret();
}

echo "Key generation completed successfully!\n";
?>
