{% extends 'base.html' %}
{% load i18n %}

{% block content %}
<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">

  <!-- Header -->
  <div class="flex items-center justify-between">
    <div>
      <h1 class="text-xl font-bold text-gray-900 flex items-center gap-2">
        <i class="fas fa-cog text-gray-500"></i> Router Monitor Settings
      </h1>
      <p class="text-sm text-gray-400 mt-0.5">UDP syslog receiver configuration</p>
    </div>
    <a href="{% url 'routermon-dashboard' %}"
       class="inline-flex items-center px-3 py-1.5 bg-gray-100 text-gray-600 text-sm rounded-md hover:bg-gray-200">
      <i class="fas fa-arrow-left mr-1.5"></i> Dashboard
    </a>
  </div>

  {% for msg in messages %}
  <div class="px-4 py-2 rounded-md text-sm border
    {% if msg.tags == 'success' %}bg-green-50 text-green-800 border-green-200
    {% elif msg.tags == 'error' %}bg-red-50 text-red-800 border-red-200
    {% else %}bg-blue-50 text-blue-800 border-blue-200{% endif %}">
    {{ msg }}
  </div>
  {% endfor %}

  <!-- Receiver settings -->
  <div class="bg-white shadow-sm rounded-lg border border-gray-200 overflow-hidden">
    <div class="px-6 py-4 bg-gray-50 border-b border-gray-200">
      <h2 class="text-sm font-semibold text-gray-700">Receiver Configuration</h2>
      <p class="text-xs text-gray-400 mt-0.5">
        The server listens for UDP syslog datagrams from your ASUS router's dnsmasq daemon.
      </p>
    </div>
    <form method="post" class="p-6 space-y-4">
      {% csrf_token %}
      {% for field in form %}
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">{{ field.label }}</label>
        {{ field }}
        {% if field.help_text %}<p class="text-xs text-gray-400 mt-1">{{ field.help_text }}</p>{% endif %}
        {% for error in field.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
      </div>
      {% endfor %}
      <div class="pt-1">
        <button type="submit"
                class="inline-flex items-center px-5 py-2 bg-indigo-600 text-white text-sm font-medium rounded-md hover:bg-indigo-700">
          <i class="fas fa-save mr-2"></i> Save Settings
        </button>
      </div>
    </form>
  </div>

  <!-- Router setup guide -->
  <div class="bg-white shadow-sm rounded-lg border border-gray-200 overflow-hidden">
    <div class="px-6 py-4 bg-blue-50 border-b border-blue-200 flex items-start gap-3">
      <i class="fas fa-info-circle text-blue-500 mt-0.5"></i>
      <div>
        <h2 class="text-sm font-semibold text-blue-800">Router Setup — AsusWRT-Merlin 3006.x (SSH method)</h2>
        <p class="text-xs text-blue-700 mt-0.5">
          SSH into your ASUS GT-AX6000 and run the commands below. This works on all Merlin 3006.x builds.
        </p>
      </div>
    </div>
    <div class="p-6 space-y-5 text-sm text-gray-700">

      <!-- Prerequisites -->
      <div class="bg-amber-50 border border-amber-200 rounded-md p-4 text-xs text-amber-800">
        <strong>Prerequisite:</strong> Enable SSH in the Merlin UI first —
        <strong>Administration → System → SSH Daemon</strong>, set to LAN only, then save.
        Also enable <strong>JFFS custom scripts and configs</strong> on the same page if not already enabled.
      </div>

      <div class="space-y-3">
        <h3 class="font-semibold text-gray-800 flex items-center gap-2">
          <span class="w-6 h-6 rounded-full bg-indigo-100 text-indigo-700 text-xs font-bold flex items-center justify-center">1</span>
          Enable DNS query logging in dnsmasq
        </h3>
        <p class="text-gray-600 text-xs ml-8">
          SSH into the router and add a dnsmasq option that persists across reboots via JFFS:
        </p>
        <pre class="bg-gray-900 text-green-300 text-xs rounded p-3 overflow-x-auto ml-8"><code>ssh admin@192.168.1.1

# Add log-queries to dnsmasq (persistent via JFFS)
echo "log-queries" >> /jffs/configs/dnsmasq.conf.add

# Apply immediately (no reboot needed)
service restart_dnsmasq</code></pre>
      </div>

      <div class="space-y-3">
        <h3 class="font-semibold text-gray-800 flex items-center gap-2">
          <span class="w-6 h-6 rounded-full bg-indigo-100 text-indigo-700 text-xs font-bold flex items-center justify-center">2</span>
          Configure remote syslog forwarding
        </h3>
        <p class="text-gray-600 text-xs ml-8">
          Set nvram variables to forward syslog to this server, then restart the syslog daemon:
        </p>
        <pre class="bg-gray-900 text-green-300 text-xs rounded p-3 overflow-x-auto ml-8"><code># Still in the SSH session:
nvram set log_remote=1
nvram set log_ipaddr=192.168.1.2
nvram set log_port={{ settings.syslog_port }}
nvram commit

service restart_syslog</code></pre>
        <p class="text-gray-500 text-xs ml-8">
          DNS queries should appear on the dashboard within a few seconds of the next DNS lookup on your network.
        </p>
      </div>

      <div class="space-y-3">
        <h3 class="font-semibold text-gray-800 flex items-center gap-2">
          <span class="w-6 h-6 rounded-full bg-indigo-100 text-indigo-700 text-xs font-bold flex items-center justify-center">3</span>
          Verify syslog is arriving
        </h3>
        <pre class="bg-gray-900 text-green-300 text-xs rounded p-3 overflow-x-auto ml-8"><code># On the k3s node (192.168.1.2) — listen for UDP packets:
nc -ulk {{ settings.syslog_port }}

# Or watch with tcpdump:
tcpdump -i any -A udp port {{ settings.syslog_port }}

# You should see lines like:
# dnsmasq[1234]: query[A] google.com from 192.168.1.x
# dnsmasq[1234]: reply google.com is 142.250.80.46</code></pre>
      </div>

      <!-- Port note -->
      <div class="bg-gray-50 border border-gray-200 rounded-md p-4">
        <h4 class="text-xs font-semibold text-gray-700 mb-2 flex items-center gap-1.5">
          <i class="fas fa-info-circle text-gray-400"></i>
          If port {{ settings.syslog_port }} is not reachable from the router
        </h4>
        <p class="text-xs text-gray-600 mb-2">
          If the router can only send to the standard syslog port (514), redirect it on the k3s node:
        </p>
        <pre class="bg-gray-900 text-green-300 text-xs rounded p-3 overflow-x-auto"><code># On the k3s node, run as root — then change log_port to 514 in nvram above
iptables -t nat -A PREROUTING -p udp --dport 514 -j REDIRECT --to-port {{ settings.syslog_port }}

# Persist across reboots (Debian/Ubuntu):
apt install iptables-persistent && netfilter-persistent save</code></pre>
      </div>

      <!-- WAN incoming traffic logging -->
      <div class="bg-blue-50 border border-blue-200 rounded-md p-4">
        <h4 class="text-xs font-semibold text-blue-800 mb-2">Step 5 — Log WAN incoming connection attempts (optional)</h4>
        <p class="text-xs text-gray-600 mb-2">
          Add iptables rules that log every new incoming connection from the WAN interface.
          The router syslog will forward these kernel messages alongside DNS logs.
          Create or edit <code class="bg-gray-100 px-1 rounded">/jffs/scripts/firewall-start</code> and add:
        </p>
        <pre class="bg-gray-900 text-green-300 text-xs rounded p-3 overflow-x-auto"><code>#!/bin/sh
# /jffs/scripts/firewall-start — runs after each firewall restart

# Auto-detect WAN interface (eth0, ppp0, vlan2, …)
WAN_IF=$(nvram get wan0_ifname 2>/dev/null)
[ -z "$WAN_IF" ] && WAN_IF=$(ip route | grep default | awk '{print $5}' | head -1)

if [ -z "$WAN_IF" ]; then
  logger -t firewall-start "Could not detect WAN interface, skipping WAN logging rules"
  exit 0
fi

logger -t firewall-start "Adding WAN logging rules on $WAN_IF"

# Log new connections TO the router (management, VPN, etc.)
iptables -I INPUT -i "$WAN_IF" -m state --state NEW \
  -m limit --limit 60/min --limit-burst 100 \
  -j LOG --log-prefix "WAN_IN: " --log-level 6

# Log new connections FORWARDED to LAN devices (port-forwarding rules)
iptables -I FORWARD -i "$WAN_IF" -m state --state NEW \
  -m limit --limit 60/min --limit-burst 100 \
  -j LOG --log-prefix "WAN_IN: " --log-level 6</code></pre>
        <p class="text-xs text-gray-500 mt-2">Make the script executable and run it once:</p>
        <pre class="bg-gray-900 text-green-300 text-xs rounded p-3 overflow-x-auto mt-1"><code>chmod +x /jffs/scripts/firewall-start
/jffs/scripts/firewall-start</code></pre>
        <p class="text-xs text-gray-500 mt-2">
          The <code class="bg-gray-100 px-1 rounded">--limit 60/min</code> rate limit protects against syslog floods during port scans.
          Rules are automatically re-applied after each firewall restart.
        </p>
      </div>

      <!-- Revert -->
      <div class="bg-gray-50 border border-gray-200 rounded-md p-4">
        <h4 class="text-xs font-semibold text-gray-700 mb-2">To disable / revert</h4>
        <pre class="bg-gray-900 text-green-300 text-xs rounded p-3 overflow-x-auto"><code>ssh admin@192.168.1.1

# Remove dnsmasq log-queries line
sed -i '/^log-queries$/d' /jffs/configs/dnsmasq.conf.add

# Remove WAN logging rules (if added)
rm -f /jffs/scripts/firewall-start
# Flush current rules:
iptables -D INPUT -j LOG --log-prefix "WAN_IN: " 2>/dev/null || true
iptables -D FORWARD -j LOG --log-prefix "WAN_IN: " 2>/dev/null || true

# Disable remote syslog
nvram set log_remote=0
nvram commit

service restart_dnsmasq
service restart_syslog</code></pre>
      </div>

    </div>
  </div>

  <!-- Current status -->
  <div class="bg-white shadow-sm rounded-lg border border-gray-200 p-5">
    <h2 class="text-sm font-semibold text-gray-700 mb-3">Receiver Status</h2>
    <dl class="grid grid-cols-2 gap-x-6 gap-y-2 text-sm">
      <dt class="text-gray-500">Status</dt>
      <dd class="font-medium {% if settings.enabled %}text-green-600{% else %}text-gray-400{% endif %}">
        {% if settings.enabled %}Enabled (listening on UDP :{{ settings.syslog_port }}){% else %}Disabled{% endif %}
      </dd>
      <dt class="text-gray-500">Last received</dt>
      <dd class="font-medium text-gray-800">
        {% if settings.last_received_at %}{{ settings.last_received_at|date:"Y-m-d H:i:s" }}{% else %}Never{% endif %}
      </dd>
      <dt class="text-gray-500">Retention</dt>
      <dd class="font-medium text-gray-800">{{ settings.retention_days }} days</dd>
    </dl>
  </div>

</div>
{% endblock %}
