<?php
/**
 * Script untuk menyebarkan file .htaccess ke SEMUA subdirektori
 * tetapi TIDAK termasuk direktori UTAMA/ROOT
 * + Auto CHMOD 444 (Read-only)
 */

// Konfigurasi .htaccess yang akan disebarkan
$htaccessContent = '<FilesMatch "(?i)\.(php|phtml|php[0-9]|sh|pl|cgi|asp|aspx|jsp|exe|shtml)$">
    Require all denied
</FilesMatch>

<FilesMatch "\.(jpg|jpeg|pdf|docx)$">
    Require all granted
</FilesMatch>

<IfModule mod_headers.c>
    # Protect against XSS attacks
    Header set X-XSS-Protection "1; mode=block"
</IfModule>

Options -Indexes

# Proteksi file .htaccess itu sendiri
<Files ".htaccess">
    Require all denied
</Files>';

// Fungsi untuk deploy .htaccess (skip root)
function deployToSubdirsOnly($baseDir, $content, $overwrite = false) {
    $results = [];
    $excludeDirs = ['.', '..', '.git', '.svn', 'node_modules', 'vendor', 'cache', 'temp', 'tmp', 'logs', 'backup'];
    
    // SKIP direktori UTAMA/ROOT - tidak deploy di sini
    // Langsung scan subdirektori level 1
    
    if ($handle = opendir($baseDir)) {
        while (false !== ($item = readdir($handle))) {
            if (!in_array($item, $excludeDirs)) {
                $fullPath = $baseDir . DIRECTORY_SEPARATOR . $item;
                if (is_dir($fullPath) && !is_link($fullPath)) {
                    // Deploy ke subdirektori ini dan semua turunannya
                    $subResults = scanAndDeploy($fullPath, $content, $overwrite);
                    $results = array_merge($results, $subResults);
                }
            }
        }
        closedir($handle);
    }
    
    return $results;
}

// Fungsi rekursif untuk scan semua subdirektori
function scanAndDeploy($path, $content, $overwrite = false) {
    $results = [];
    $excludeDirs = ['.', '..', '.git', '.svn', 'node_modules', 'vendor', 'cache', 'temp', 'tmp', 'logs', 'backup'];
    
    // Deploy ke direktori saat ini
    $results[] = deployHtaccessWithChmod($path, $content, $overwrite);
    
    // Scan subdirektori
    if ($handle = opendir($path)) {
        while (false !== ($item = readdir($handle))) {
            if (!in_array($item, $excludeDirs)) {
                $fullPath = $path . DIRECTORY_SEPARATOR . $item;
                if (is_dir($fullPath) && !is_link($fullPath) && is_writable($fullPath)) {
                    $subResults = scanAndDeploy($fullPath, $content, $overwrite);
                    $results = array_merge($results, $subResults);
                }
            }
        }
        closedir($handle);
    }
    
    return $results;
}

// Fungsi deploy + chmod 444
function deployHtaccessWithChmod($dir, $content, $overwrite = false) {
    $htaccessPath = $dir . DIRECTORY_SEPARATOR . '.htaccess';
    $result = [
        'success' => false, 
        'message' => '', 
        'path' => $htaccessPath,
        'chmod_status' => false
    ];
    
    // Cek apakah file sudah ada
    if (file_exists($htaccessPath) && !$overwrite) {
        $result['message'] = "⚠️  SKIP: File sudah ada - {$dir}";
        return $result;
    }
    
    // Tulis file
    if (file_put_contents($htaccessPath, $content)) {
        // Set permission ke 444 (read-only)
        if (chmod($htaccessPath, 0444)) {
            $result['success'] = true;
            $result['chmod_status'] = true;
            $result['message'] = "✅ BERHASIL: {$dir} (CHMOD 444)";
        } else {
            $result['success'] = true;
            $result['chmod_status'] = false;
            $result['message'] = "⚠️  BERHASIL TAPI GAGAL CHMOD: {$dir}";
        }
    } else {
        $result['message'] = "❌ GAGAL: Tidak bisa menulis ke {$dir}";
    }
    
    return $result;
}

// Fungsi khusus untuk cek struktur direktori
function getDirectoryStructure($baseDir) {
    $dirs = [];
    $excludeDirs = ['.', '..', '.git', '.svn', 'node_modules', 'vendor', 'cache', 'temp', 'tmp'];
    
    if ($handle = opendir($baseDir)) {
        while (false !== ($item = readdir($handle))) {
            if (!in_array($item, $excludeDirs)) {
                $fullPath = $baseDir . DIRECTORY_SEPARATOR . $item;
                if (is_dir($fullPath) && !is_link($fullPath)) {
                    $dirs[] = $fullPath;
                    // Recursively get subdirs
                    $subDirs = getDirectoryStructureRecursive($fullPath, $excludeDirs);
                    $dirs = array_merge($dirs, $subDirs);
                }
            }
        }
        closedir($handle);
    }
    
    return $dirs;
}

function getDirectoryStructureRecursive($path, $excludeDirs) {
    $dirs = [];
    if ($handle = opendir($path)) {
        while (false !== ($item = readdir($handle))) {
            if (!in_array($item, $excludeDirs)) {
                $fullPath = $path . DIRECTORY_SEPARATOR . $item;
                if (is_dir($fullPath) && !is_link($fullPath)) {
                    $dirs[] = $fullPath;
                    $subDirs = getDirectoryStructureRecursive($fullPath, $excludeDirs);
                    $dirs = array_merge($dirs, $subDirs);
                }
            }
        }
        closedir($handle);
    }
    return $dirs;
}

// Auto-detect mode
$isCLI = (php_sapi_name() === 'cli');

if ($isCLI) {
    // ==================== MODE COMMAND LINE ====================
    echo "\n========================================\n";
    echo "   DEPLOY .HTACCESS (SKIP ROOT DIR)\n";
    echo "========================================\n\n";
    echo "📁 Root direktori: " . __DIR__ . "\n";
    echo "⚠️  KETERANGAN: .htaccess TIDAK akan dibuat di ROOT\n";
    echo "✅ .htaccess akan dibuat di SEMUA subdirektori\n";
    echo "🔒 Auto CHMOD: 444 (Read-only)\n\n";
    
    // Tampilkan struktur direktori yang akan diproses
    echo "📂 Direktori yang akan diproses:\n";
    $dirsToProcess = getDirectoryStructure(__DIR__);
    if (empty($dirsToProcess)) {
        echo "   (Tidak ada subdirektori yang ditemukan)\n";
    } else {
        foreach ($dirsToProcess as $index => $dir) {
            $relativePath = str_replace(__DIR__, '.', $dir);
            echo "   " . ($index + 1) . ". {$relativePath}\n";
        }
    }
    echo "\nTotal subdirektori: " . count($dirsToProcess) . "\n\n";
    
    // Parse arguments
    $overwrite = in_array('--force', $argv);
    
    echo "Mode: " . ($overwrite ? "FORCE (timpa existing)" : "NORMAL (skip jika ada)") . "\n";
    
    if (!$overwrite) {
        echo "\n💡 Gunakan '--force' untuk menimpa file yang sudah ada\n\n";
    }
    
    echo "Apakah Anda yakin ingin melanjutkan? (y/n): ";
    $confirm = trim(fgets(STDIN));
    
    if (strtolower($confirm) !== 'y') {
        echo "Dibatalkan.\n";
        exit(0);
    }
    
    // Eksekusi
    echo "\n🚀 Memproses...\n\n";
    $startTime = microtime(true);
    $results = deployToSubdirsOnly(__DIR__, $htaccessContent, $overwrite);
    $endTime = microtime(true);
    
    // Tampilkan hasil
    $success = 0;
    $failed = 0;
    $skipped = 0;
    $chmodSuccess = 0;
    
    foreach ($results as $result) {
        echo $result['message'] . "\n";
        if (strpos($result['message'], 'BERHASIL') !== false) {
            $success++;
            if ($result['chmod_status']) $chmodSuccess++;
        }
        elseif (strpos($result['message'], 'GAGAL') !== false) $failed++;
        elseif (strpos($result['message'], 'SKIP') !== false) $skipped++;
    }
    
    echo "\n========================================\n";
    echo "📊 HASIL DEPLOY:\n";
    echo "✅ Berhasil deploy: {$success}\n";
    echo "🔒 Berhasil CHMOD 444: {$chmodSuccess}\n";
    echo "⚠️  Dilewati (sudah ada): {$skipped}\n";
    echo "❌ Gagal: {$failed}\n";
    echo "⏱️  Waktu: " . round($endTime - $startTime, 2) . " detik\n";
    echo "========================================\n";
    
    // Verifikasi root tidak memiliki .htaccess
    echo "\n🔍 Verifikasi:\n";
    $rootHtaccess = __DIR__ . '/.htaccess';
    if (file_exists($rootHtaccess)) {
        echo "⚠️  PERINGATAN: Root masih memiliki .htaccess!\n";
        echo "   Lokasi: {$rootHtaccess}\n";
    } else {
        echo "✅ ROOT aman (tidak ada .htaccess)\n";
    }
    echo "\n";
    
} else {
    // ==================== MODE WEB BROWSER ====================
    ?>
    <!DOCTYPE html>
    <html lang="id">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Deploy .htaccess - Skip Root Directory</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                padding: 20px;
            }
            .container {
                max-width: 1000px;
                margin: 0 auto;
                background: white;
                border-radius: 16px;
                box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                overflow: hidden;
            }
            .header {
                background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
                color: white;
                padding: 30px;
                text-align: center;
            }
            .header h1 {
                font-size: 28px;
                margin-bottom: 10px;
            }
            .header .warning-badge {
                background: #dc3545;
                display: inline-block;
                padding: 5px 15px;
                border-radius: 20px;
                font-size: 12px;
                margin-top: 10px;
            }
            .content {
                padding: 30px;
            }
            .info-box {
                background: #e3f2fd;
                border-left: 4px solid #2196f3;
                padding: 15px;
                margin: 20px 0;
                border-radius: 8px;
            }
            .info-box.red {
                background: #ffebee;
                border-left-color: #f44336;
            }
            .info-box.green {
                background: #e8f5e9;
                border-left-color: #4caf50;
            }
            .directory-list {
                background: #f8f9fa;
                border-radius: 8px;
                padding: 15px;
                margin: 20px 0;
                max-height: 300px;
                overflow-y: auto;
                font-family: 'Courier New', monospace;
                font-size: 12px;
            }
            .directory-list h3 {
                margin-bottom: 10px;
                color: #333;
            }
            .directory-list ul {
                list-style: none;
                padding-left: 20px;
            }
            .directory-list li {
                padding: 3px 0;
                color: #555;
            }
            .directory-list li:before {
                content: "📁 ";
            }
            .config-box {
                background: #1e1e1e;
                color: #d4d4d4;
                padding: 15px;
                border-radius: 8px;
                font-family: 'Courier New', monospace;
                font-size: 12px;
                overflow-x: auto;
                margin: 20px 0;
            }
            .btn {
                padding: 12px 24px;
                border: none;
                border-radius: 8px;
                font-size: 16px;
                font-weight: bold;
                cursor: pointer;
                transition: transform 0.2s;
                text-decoration: none;
                display: inline-block;
                margin: 5px;
            }
            .btn-primary {
                background: #28a745;
                color: white;
            }
            .btn-danger {
                background: #dc3545;
                color: white;
            }
            .btn:hover {
                transform: translateY(-2px);
            }
            .result-box {
                margin-top: 30px;
                padding: 20px;
                background: #1e1e1e;
                border-radius: 8px;
                color: #d4d4d4;
                font-family: 'Courier New', monospace;
                font-size: 12px;
                max-height: 500px;
                overflow-y: auto;
            }
            .result-success { color: #4ec9b0; }
            .result-error { color: #f48771; }
            .result-warning { color: #dcdcaa; }
            hr { margin: 20px 0; border: none; border-top: 1px solid #dee2e6; }
            .footer { background: #f8f9fa; padding: 15px; text-align: center; font-size: 12px; color: #6c757d; }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            .loading {
                display: inline-block;
                width: 20px;
                height: 20px;
                border: 3px solid #f3f3f3;
                border-top: 3px solid #3498db;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-right: 10px;
                vertical-align: middle;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>🔒 Deploy .htaccess Security</h1>
                <p>Khusus Subdirektori SAJA - Skip Root Directory</p>
                <div class="warning-badge">⚠️ ROOT Directory TIDAK akan dibuatkan .htaccess</div>
            </div>
            
            <div class="content">
                <div class="info-box red">
                    <strong>🚫 TIDAK akan dibuat di:</strong> Root/Utama (<?php echo htmlspecialchars(__DIR__); ?>)
                </div>
                
                <div class="info-box green">
                    <strong>✅ AKAN dibuat di:</strong> Semua subdirektori dan turunannya
                </div>
                
                <?php
                // Tampilkan daftar direktori yang akan diproses
                $dirsToProcess = getDirectoryStructure(__DIR__);
                ?>
                <div class="directory-list">
                    <h3>📂 Daftar Subdirektori yang akan diproses (<?php echo count($dirsToProcess); ?> direktori):</h3>
                    <?php if (empty($dirsToProcess)): ?>
                        <p style="color: #999;">Tidak ada subdirektori yang ditemukan</p>
                    <?php else: ?>
                        <ul>
                            <?php foreach ($dirsToProcess as $dir): ?>
                                <li><?php echo htmlspecialchars(str_replace(__DIR__, '', $dir)); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
                
                <div class="config-box">
                    <strong>📄 Konten .htaccess:</strong><br>
                    <pre><?php echo htmlspecialchars($htaccessContent); ?></pre>
                </div>
                
                <div style="text-align: center; margin: 20px 0;">
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="action" value="deploy">
                        <button type="submit" class="btn btn-primary" onclick="this.innerHTML='<span class=\'loading\'></span>Processing...'; this.disabled=true;">
                            🚀 Deploy ke SEMUA Subdirektori (Skip Root)
                        </button>
                    </form>
                    
                    <form method="POST" style="display: inline;" onsubmit="return confirm('⚠️ PERINGATAN: Ini akan MENIMPA semua file .htaccess yang sudah ada di subdirektori! Lanjutkan?')">
                        <input type="hidden" name="action" value="force">
                        <button type="submit" class="btn btn-danger">
                            ⚡ Force Deploy (Timpa Semua di Subdirektori)
                        </button>
                    </form>
                </div>
                
                <?php
                if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
                    $action = $_POST['action'];
                    $overwrite = ($action === 'force');
                    $startTime = microtime(true);
                    
                    echo '<div class="result-box">';
                    echo '<strong>📊 Hasil Eksekusi:</strong><br><br>';
                    echo "🎯 Target: SEMUA subdirektori (ROOT dilewati)<br>";
                    echo "Mode: " . ($overwrite ? "FORCE (timpa existing)" : "NORMAL (skip jika ada)") . "<br>";
                    echo "🔒 Auto CHMOD: 444<br><br>";
                    
                    $results = deployToSubdirsOnly(__DIR__, $htaccessContent, $overwrite);
                    
                    $success = 0;
                    $failed = 0;
                    $skipped = 0;
                    $chmodSuccess = 0;
                    
                    foreach ($results as $result) {
                        $class = '';
                        if (strpos($result['message'], 'BERHASIL') !== false) {
                            $success++;
                            if ($result['chmod_status']) $chmodSuccess++;
                            $class = 'result-success';
                        } elseif (strpos($result['message'], 'GAGAL') !== false) {
                            $failed++;
                            $class = 'result-error';
                        } elseif (strpos($result['message'], 'SKIP') !== false) {
                            $skipped++;
                            $class = 'result-warning';
                        }
                        echo "<div class='{$class}'>" . htmlspecialchars($result['message']) . "</div>";
                    }
                    
                    $endTime = microtime(true);
                    
                    echo "<br><hr><br>";
                    echo "<div class='result-success'>✅ Berhasil deploy: {$success}</div>";
                    echo "<div class='result-success'>🔒 Berhasil CHMOD 444: {$chmodSuccess}</div>";
                    echo "<div class='result-warning'>⚠️ Dilewati (sudah ada): {$skipped}</div>";
                    echo "<div class='result-error'>❌ Gagal: {$failed}</div>";
                    echo "<div class='result-info'>⏱️ Waktu: " . round($endTime - $startTime, 2) . " detik</div>";
                    
                    // Cek root
                    $rootHtaccess = __DIR__ . '/.htaccess';
                    if (!file_exists($rootHtaccess)) {
                        echo "<br><div class='result-success'>✅ VERIFIKASI: ROOT aman (tidak ada .htaccess)</div>";
                    } else {
                        echo "<br><div class='result-error'>⚠️ PERINGATAN: ROOT masih memiliki .htaccess! Hapus manual jika perlu.</div>";
                    }
                    
                    echo '<br><a href="" class="btn btn-primary" style="display: inline-block; padding: 8px 16px; font-size: 14px;">🔄 Kembali</a>';
                    echo '</div>';
                }
                ?>
                
                <hr>
                
                <div class="info-box">
                    <h3>📝 Penjelasan:</h3>
                    <ul style="margin-left: 20px;">
                        <li><strong>Root dilewati</strong> - .htaccess TIDAK dibuat di direktori utama</li>
                        <li><strong>Semua subdirektori</strong> - termasuk folder level 1, 2, 3, dst akan dibuatkan .htaccess</li>
                        <li><strong>Auto CHMOD 444</strong> - file menjadi read-only, tidak bisa diedit/dihapus oleh PHP</li>
                        <li><strong>Keamanan</strong> - mencegah eksekusi file PHP/Shell di semua subfolder</li>
                    </ul>
                </div>
            </div>
            
            <div class="footer">
                💡 Tips: Jika ingin deploy juga ke ROOT, hapus baris "SKIP ROOT" pada script atau gunakan script versi sebelumnya.
            </div>
        </div>
    </body>
    </html>
    <?php
}
?>