#!/bin/bash
# wml-fix - one-shot recovery script.
#
# If anything is wrong with the installed system (services failing, no NAT,
# no DHCP, wizard error), the user can just type `wml-fix` at the console
# and this script re-runs all the post-install setup to bring everything
# to a clean working state.
#
# Safe to run multiple times. Idempotent.

set -u

GREEN=$'\033[32m'
PINK=$'\033[38;5;205m'
BOLD=$'\033[1m'
RESET=$'\033[0m'

echo
echo "${PINK}${BOLD}WML OS Recovery Tool${RESET}"
echo "Re-running all setup steps to bring the firewall to a healthy state..."
echo

# 1. Ensure root is mounted read-write
if mount | grep -q ' / .*ro,'; then
    echo "[1/7] Remounting / as read-write..."
    mount -o remount,rw /
else
    echo "[1/7] Root filesystem is already read-write"
fi

# 2. Re-run wml-firstboot (it's idempotent thanks to ConditionPathExists guard,
#    but we force-delete the marker so it definitely runs)
echo "[2/7] Re-running wml-firstboot..."
rm -f /var/lib/wml/firstboot-done
/usr/local/sbin/wml-firstboot

# 3. Explicit NAT + forwarding (paranoid - firstboot already did this but be sure)
echo "[3/7] Enabling NAT + IP forwarding..."
sysctl -w net.ipv4.ip_forward=1 >/dev/null
sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null

WAN_IF=$(awk -F= '/^WAN_IF=/{print $2}' /etc/wml/interfaces.conf 2>/dev/null)
LAN_IF=$(awk -F= '/^LAN_IF=/{print $2}' /etc/wml/interfaces.conf 2>/dev/null)
echo "    WAN=$WAN_IF  LAN=$LAN_IF"

if [[ -n "$WAN_IF" ]]; then
    nft flush ruleset 2>/dev/null
    nft add table ip wml-nat 2>/dev/null
    nft 'add chain ip wml-nat postrouting { type nat hook postrouting priority 100; }' 2>/dev/null
    nft "add rule ip wml-nat postrouting oifname \"$WAN_IF\" masquerade" 2>/dev/null
    nft add table inet wml-filter 2>/dev/null
    nft 'add chain inet wml-filter forward { type filter hook forward priority 0; policy accept; }' 2>/dev/null
fi

# 4. Restart all firewall services in order
echo "[4/7] Restarting services..."
systemctl restart systemd-networkd 2>/dev/null
sleep 2
systemctl restart unbound 2>/dev/null
systemctl restart kea-dhcp4-server 2>/dev/null
systemctl restart nginx 2>/dev/null
systemctl restart wml-api 2>/dev/null

# 5. Verify nginx vhost
echo "[5/7] Verifying nginx WML vhost..."
if [[ ! -L /etc/nginx/sites-enabled/wml-admin ]]; then
    rm -f /etc/nginx/sites-enabled/default
    ln -sf /etc/nginx/sites-available/wml-admin /etc/nginx/sites-enabled/wml-admin
    systemctl reload nginx
fi

# 6. Status
echo "[6/7] Service status:"
for svc in wml-api nginx kea-dhcp4-server unbound nftables; do
    state=$(systemctl is-active "$svc" 2>/dev/null)
    if [[ "$state" == "active" ]]; then
        printf "    ${GREEN}✓${RESET} %-22s %s\n" "$svc" "$state"
    else
        printf "    ${PINK}✗${RESET} %-22s %s\n" "$svc" "$state"
    fi
done

# 7. Show IPs
echo "[7/7] Network state:"
ip -br addr | grep -vE '^(lo|docker|veth)' | while read -r line; do
    echo "    $line"
done

echo
echo "${GREEN}${BOLD}Done.${RESET} Admin UI: ${BOLD}http://172.30.30.1/${RESET}"
echo "Login: ${BOLD}root${RESET} + the password you set at install"
echo
