#!/usr/bin/env bash
# ==============================================================================
# /usr/local/bin/setup-t490-gateway.sh
# Homelab Zero-Leak Edge Gateway 1-Shot Installer for ThinkPad T490
# Target OS: Ubuntu Server 24.04 LTS / Debian 12
# ==============================================================================
set -euo pipefail

# Ensure running as root
if [ "$EUID" -ne 0 ]; then
    echo "❌ Error: This script must be run as root (use sudo bash $0)" >&2
    exit 1
fi

WLAN_IF="${1:-wlan0}"
ETH_IF="${2:-enp0s31f6}"
SSID="${3:-FriendsWiFiSSID}"
WIFI_PASS="${4:-FriendsSecureWiFiPassword}"
TRANSIT_IP="172.16.100.1"
PVE_IP="172.16.100.2"
VM_NET="192.168.45.0/24"
TRANSIT_NET="172.16.100.0/24"

echo "======================================================================"
echo "Homelab Zero-Leak Edge Gateway Setup (ThinkPad T490)"
echo "Wi-Fi Interface:    ${WLAN_IF} (Connecting to: ${SSID})"
echo "Ethernet Interface: ${ETH_IF} (Transit IP: ${TRANSIT_IP})"
echo "Proxmox Target:     ${PVE_IP} (Workload Subnet: ${VM_NET})"
echo "======================================================================"

# Step 1: Install prerequisite packages
echo "==> [1/7] Installing network and power management utilities..."
apt update -y
apt install -y nftables dnsmasq tlp tlp-rdw curl tcpdump iw wireless-tools net-tools

# Step 2: Apply Kernel Hardening & sysctl policies
echo "==> [2/7] Applying Kernel Hardening & Zero-Leak sysctl policy..."
cat << EOF > /etc/sysctl.d/99-homelab-gateway-hardening.conf
net.ipv4.ip_forward = 1
net.ipv6.conf.all.forwarding = 0
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.${WLAN_IF}.disable_ipv6 = 1
net.ipv6.conf.${ETH_IF}.disable_ipv6 = 1

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.${WLAN_IF}.send_redirects = 0
net.ipv4.conf.${ETH_IF}.send_redirects = 0

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.${WLAN_IF}.accept_redirects = 0

net.ipv4.conf.all.proxy_arp = 0
net.ipv4.conf.default.proxy_arp = 0
net.ipv4.conf.${WLAN_IF}.proxy_arp = 0
net.ipv4.conf.${ETH_IF}.proxy_arp = 0

net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.${WLAN_IF}.arp_ignore = 1
net.ipv4.conf.${ETH_IF}.arp_ignore = 1

net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.${WLAN_IF}.arp_announce = 2
net.ipv4.conf.${ETH_IF}.arp_announce = 2

net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.${WLAN_IF}.rp_filter = 1
net.ipv4.conf.${ETH_IF}.rp_filter = 1
EOF
sysctl -p /etc/sysctl.d/99-homelab-gateway-hardening.conf

# Step 3: Write Netplan Configuration
echo "==> [3/7] Configuring Netplan interfaces..."
cat << EOF > /etc/netplan/01-homelab-gateway.yaml
network:
  version: 2
  renderer: networkd
  ethernets:
    ${ETH_IF}:
      dhcp4: false
      dhcp6: false
      addresses:
        - ${TRANSIT_IP}/24
      routes:
        - to: ${VM_NET}
          via: ${PVE_IP}
          metric: 100
      link-local: []
  wifis:
    ${WLAN_IF}:
      dhcp4: true
      dhcp4-overrides:
        route-metric: 50
        use-dns: true
      access-points:
        "${SSID}":
          password: "${WIFI_PASS}"
EOF
chmod 600 /etc/netplan/01-homelab-gateway.yaml
netplan apply || true

# Step 4: Configure Atomic nftables Engine
echo "==> [4/7] Deploying atomic nftables firewall & single MASQUERADE..."
cat << EOF > /etc/nftables.conf
#!/usr/sbin/nft -f
flush ruleset

table inet homelab_filter {
    flowtable fastpath {
        hook ingress priority 0;
        devices = { ${WLAN_IF}, ${ETH_IF} };
    }

    chain input {
        type filter hook input priority filter; policy drop;
        iifname "lo" accept
        ct state established,related accept
        ct state invalid drop

        iifname "${ETH_IF}" ip protocol icmp accept
        iifname "${ETH_IF}" udp dport { 53, 67 } accept
        iifname "${ETH_IF}" tcp dport 53 accept
        iifname "${ETH_IF}" ip saddr { ${TRANSIT_NET}, ${VM_NET} } tcp dport 22 accept

        iifname "tailscale0" accept
        udp dport 41641 accept

        iifname "${WLAN_IF}" udp sport 67 udp dport 68 accept
        iifname "${WLAN_IF}" drop
    }

    chain forward {
        type filter hook forward priority filter; policy drop;
        ip protocol { tcp, udp } flow offload @fastpath
        tcp flags syn tcp option maxseg size set rt mtu

        ct state established,related accept
        ct state invalid drop

        iifname "${ETH_IF}" oifname "${WLAN_IF}" ip daddr { 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12 } drop
        iifname "${ETH_IF}" oifname "${WLAN_IF}" ip saddr { ${TRANSIT_NET}, ${VM_NET} } accept
        iifname "tailscale0" oifname "${ETH_IF}" accept
        iifname "${ETH_IF}" oifname "tailscale0" accept
        drop
    }

    chain output {
        type filter hook output priority filter; policy accept;
        oifname "${WLAN_IF}" udp dport { 5353, 5355, 137, 138, 1900, 3702 } drop
        oifname "${WLAN_IF}" tcp dport { 139, 445 } drop
        oifname "${WLAN_IF}" ip daddr { 224.0.0.0/4, 255.255.255.255 } drop
    }
}

table inet homelab_nat {
    chain postrouting {
        type nat hook postrouting priority srcnat; policy accept;
        oifname "${WLAN_IF}" ip saddr { ${TRANSIT_NET}, ${VM_NET} } masquerade
    }
}
EOF
systemctl enable --now nftables

# Step 5: Configure Isolated dnsmasq Service
echo "==> [5/7] Configuring isolated transit dnsmasq..."
cat << EOF > /etc/dnsmasq.d/homelab-transit.conf
bind-interfaces
interface=${ETH_IF}
interface=lo
except-interface=${WLAN_IF}
no-dhcp-interface=${WLAN_IF}
listen-address=${TRANSIT_IP}
dhcp-range=${ETH_IF},172.16.100.10,172.16.100.50,255.255.255.0,12h
dhcp-option=${ETH_IF},3,${TRANSIT_IP}
dhcp-option=${ETH_IF},6,${TRANSIT_IP},1.1.1.1,9.9.9.9
domain-needed
bogus-priv
no-resolv
server=1.1.1.1
server=9.9.9.9
cache-size=4096
EOF
systemctl restart dnsmasq || true
systemctl enable dnsmasq || true

# Step 6: Hardware Lifecycle, Lid-Closed Mode & Battery Health
echo "==> [6/7] Configuring ThinkPad hardware lifecycle and TLP..."
mkdir -p /etc/systemd/logind.conf.d /etc/tlp.d /etc/modprobe.d

cat << EOF > /etc/systemd/logind.conf.d/homelab-lid.conf
[Login]
HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
HandleLidSwitchDocked=ignore
LidSwitchIgnoreInhibited=no
HoldoffTimeoutSec=0
EOF
systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target || true

cat << EOF > /etc/tlp.d/01-homelab-gateway.conf
START_CHARGE_THRESH_BAT0=75
STOP_CHARGE_THRESH_BAT0=80
CPU_SCALING_GOVERNOR_ON_AC=performance
CPU_ENERGY_PERF_POLICY_ON_AC=balance_performance
WIFI_PWR_ON_AC=off
EOF

cat << EOF > /etc/modprobe.d/iwlwifi.conf
options iwlwifi power_save=0 d0i3_disable=Y uapsd_disable=Y
options iwlmvm power_scheme=1
EOF

tlp start || true

# Step 7: Complete
echo "======================================================================"
echo "✅ ThinkPad T490 Zero-Leak Gateway is fully configured and online!"
echo "   Transit Gateway IP: ${TRANSIT_IP}"
echo "   Connect Cat6 Ethernet cable to ThinkStation."
echo "======================================================================"
