{% extends "base.html" %}
{% block title %}Linux Defense — AUTARCH{% endblock %}

{% block content %}
<div class="page-header" style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap">
    <div>
        <h1>Linux Defense</h1>
        <p style="margin:0;font-size:0.85rem;color:var(--text-secondary)">
            System hardening, iptables firewall management, and log analysis
        </p>
    </div>
    <a href="{{ url_for('defense.index') }}" class="btn btn-sm" style="margin-left:auto">&larr; Defense</a>
</div>

<!-- Security Audit -->
<div class="card">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem;flex-wrap:wrap;gap:0.5rem">
        <h3 style="margin:0">Security Audit</h3>
        <button id="btn-audit" class="btn btn-primary btn-sm" onclick="linuxRunAudit()">Run Full Audit</button>
    </div>
    <div style="display:flex;gap:24px;align-items:flex-start;flex-wrap:wrap">
        <div style="text-align:center;padding:12px 20px;background:var(--bg-primary);border:1px solid var(--border);border-radius:var(--radius);min-width:120px">
            <div id="audit-score" style="font-size:2.5rem;font-weight:700;line-height:1">--</div>
            <div style="font-size:0.78rem;color:var(--text-secondary);margin-top:4px">Security Score</div>
        </div>
        <div style="flex:1;min-width:280px">
            <table class="data-table">
                <thead><tr><th>Check</th><th>Status</th><th>Details</th></tr></thead>
                <tbody id="audit-results">
                    <tr><td colspan="3" class="empty-state">Run an audit to see results.</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Quick Checks -->
<div class="card">
    <h3>Quick Checks</h3>
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:10px">
        {% for check_id, check_name, check_desc in [
            ('firewall', 'Firewall', 'Check iptables/ufw/firewalld status'),
            ('ssh', 'SSH Config', 'Check SSH hardening settings'),
            ('ports', 'Open Ports', 'Scan for high-risk listening ports'),
            ('users', 'Users', 'Check UID 0 users and empty passwords'),
            ('permissions', 'Permissions', 'Check critical file permissions'),
            ('services', 'Services', 'Check for dangerous services')
        ] %}
        <div style="background:var(--bg-primary);border:1px solid var(--border);border-radius:var(--radius);padding:14px">
            <div style="font-weight:600;font-size:0.88rem;margin-bottom:4px">{{ check_name }}</div>
            <div style="color:var(--text-secondary);font-size:0.78rem;margin-bottom:10px">{{ check_desc }}</div>
            <button class="btn btn-sm" style="width:100%" onclick="linuxRunCheck('{{ check_id }}')">Run</button>
            <pre class="output-panel tool-result" id="check-result-{{ check_id }}" style="display:none;margin-top:10px;font-size:0.75rem;min-height:0"></pre>
        </div>
        {% endfor %}
    </div>
</div>

<!-- Firewall Manager -->
<div class="card">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem;flex-wrap:wrap;gap:0.5rem">
        <h3 style="margin:0">Firewall Manager (iptables)</h3>
        <button class="btn btn-sm" onclick="linuxLoadFwRules()">Refresh Rules</button>
    </div>
    <pre class="output-panel" id="fw-rules" style="max-height:300px;overflow-y:auto">Click "Refresh Rules" to load current iptables rules.</pre>
    <div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap">
        <input type="text" id="block-ip" class="form-control" placeholder="IP address to block" style="flex:1;min-width:180px">
        <button class="btn btn-sm btn-danger" onclick="linuxBlockIP()">Block IP</button>
        <button class="btn btn-sm" onclick="linuxUnblockIP()">Unblock IP</button>
    </div>
    <pre class="output-panel" id="fw-result" style="min-height:0;margin-top:8px"></pre>
</div>

<!-- Log Analysis -->
<div class="card">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem;flex-wrap:wrap;gap:0.5rem">
        <h3 style="margin:0">Log Analysis</h3>
        <button id="btn-logs" class="btn btn-primary btn-sm" onclick="linuxAnalyzeLogs()">Analyze Logs</button>
    </div>
    <pre class="output-panel" id="log-output" style="max-height:350px;overflow-y:auto">Click "Analyze Logs" to parse auth and web server logs.</pre>
</div>

<script>
function linuxRunAudit() {
    var btn = document.getElementById('btn-audit');
    setLoading(btn, true);
    postJSON('/defense/linux/audit', {}).then(function(data) {
        setLoading(btn, false);
        if (data.error) { renderOutput('audit-results', 'Error: ' + data.error); return; }
        var scoreEl = document.getElementById('audit-score');
        if (scoreEl) {
            scoreEl.textContent = data.score + '%';
            scoreEl.style.color = data.score >= 80 ? 'var(--success)' : data.score >= 50 ? 'var(--warning)' : 'var(--danger)';
        }
        var html = '';
        (data.checks || []).forEach(function(c) {
            html += '<tr><td>' + escapeHtml(c.name) + '</td><td><span class="badge ' + (c.passed ? 'badge-pass' : 'badge-fail') + '">'
                + (c.passed ? 'PASS' : 'FAIL') + '</span></td><td>' + escapeHtml(c.details || '') + '</td></tr>';
        });
        document.getElementById('audit-results').innerHTML = html || '<tr><td colspan="3">No results</td></tr>';
    }).catch(function() { setLoading(btn, false); });
}

function linuxRunCheck(name) {
    var el = document.getElementById('check-result-' + name);
    if (el) { el.textContent = 'Running...'; el.style.display = 'block'; }
    postJSON('/defense/linux/check/' + name, {}).then(function(data) {
        if (data.error) { if (el) el.textContent = 'Error: ' + data.error; return; }
        var lines = (data.checks || []).map(function(c) {
            return (c.passed ? '[PASS] ' : '[FAIL] ') + c.name + (c.details ? ' — ' + c.details : '');
        });
        if (el) el.textContent = lines.join('\n') || 'No results';
    }).catch(function() { if (el) el.textContent = 'Request failed'; });
}

function linuxLoadFwRules() {
    fetchJSON('/defense/linux/firewall/rules').then(function(data) {
        renderOutput('fw-rules', data.rules || 'Could not load rules');
    });
}

function linuxBlockIP() {
    var ip = document.getElementById('block-ip').value.trim();
    if (!ip) return;
    postJSON('/defense/linux/firewall/block', {ip: ip}).then(function(data) {
        renderOutput('fw-result', data.message || data.error);
        if (data.success) { document.getElementById('block-ip').value = ''; linuxLoadFwRules(); }
    });
}

function linuxUnblockIP() {
    var ip = document.getElementById('block-ip').value.trim();
    if (!ip) return;
    postJSON('/defense/linux/firewall/unblock', {ip: ip}).then(function(data) {
        renderOutput('fw-result', data.message || data.error);
        if (data.success) linuxLoadFwRules();
    });
}

function linuxAnalyzeLogs() {
    var btn = document.getElementById('btn-logs');
    setLoading(btn, true);
    postJSON('/defense/linux/logs/analyze', {}).then(function(data) {
        setLoading(btn, false);
        if (data.error) { renderOutput('log-output', 'Error: ' + data.error); return; }
        var lines = [];
        if (data.auth_results && data.auth_results.length) {
            lines.push('=== Auth Log Analysis ===');
            data.auth_results.forEach(function(r) {
                lines.push(r.ip + ': ' + r.count + ' failures (' + (r.usernames || []).join(', ') + ')');
            });
        } else { lines.push('No auth log entries found.'); }
        if (data.web_results && data.web_results.length) {
            lines.push('\n=== Web Log Analysis ===');
            data.web_results.forEach(function(r) {
                lines.push(r.ip + ': ' + r.count + ' suspicious requests');
            });
        }
        renderOutput('log-output', lines.join('\n') || 'No findings.');
    }).catch(function() { setLoading(btn, false); });
}
</script>
{% endblock %}
