#!/bin/bash
set e

echo "Updating system"
sudo apt update
sudo apt upgrade -y

echo "Installing required packages"
sudo apt install -y curl nftables

echo "Enabling IP forwarding"
sudo tee /etc/sysctl.d/99-tailscale-router.conf >/dev/null <<'EOF'
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1
EOF

sudo sysctl --system

echo "Installing Tailscale"
curl -fsSL https://tailscale.com/install.sh | sh

echo "Enabling Tailscale at boot"
sudo systemctl enable --now tailscaled

echo "Creating NAT configuration"

sudo nft list table ip tailscale_netmap >/dev/null 2>&1 || \
sudo nft add table ip tailscale_netmap

sudo nft list chain ip tailscale_netmap prerouting >/dev/null 2>&1 || \
sudo nft 'add chain ip tailscale_netmap prerouting { type nat hook prerouting priority dstnat; policy accept; }'

sudo nft list chain ip tailscale_netmap postrouting >/dev/null 2>&1 || \
sudo nft 'add chain ip tailscale_netmap postrouting { type nat hook postrouting priority srcnat; policy accept; }'

sudo nft flush chain ip tailscale_netmap prerouting
sudo nft flush chain ip tailscale_netmap postrouting

echo "Adding DNAT"

sudo nft add rule ip tailscale_netmap prerouting \
    iifname "tailscale0" \
    ip daddr 192.168.2.0/24 \
    dnat ip prefix to ip daddr map \
    { 192.168.2.0/24 : 192.168.1.0/24 }

echo "Adding SNAT"

sudo nft add rule ip tailscale_netmap postrouting \
    oifname "eth0" \
    ip saddr 100.64.0.0/10 \
    ip daddr 192.168.1.0/24 \
    snat to 192.168.1.126

echo "Saving NAT configuration"

sudo tee /etc/tailscale-netmap.nft >/dev/null <<'EOF'
table ip tailscale_netmap {
    chain prerouting {
        type nat hook prerouting priority dstnat;
        policy accept;

        iifname "tailscale0" \
        ip daddr 192.168.2.0/24 \
        dnat ip prefix to ip daddr map {
            192.168.2.0/24 : 192.168.1.0/24
        }
    }

    chain postrouting {
        type nat hook postrouting priority srcnat;
        policy accept;

        oifname "eth0" \
        ip saddr 100.64.0.0/10 \
        ip daddr 192.168.1.0/24 \
        snat to 192.168.1.126
    }
}
EOF

echo "Creating boot service"

sudo tee /etc/systemd/system/tailscale-netmap.service >/dev/null <<'EOF'
[Unit]
Description=Tailscale overlapping subnet NAT
After=network-online.target tailscaled.service
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/nft -f /etc/tailscale-netmap.nft
ExecStop=/usr/sbin/nft delete table ip tailscale_netmap

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable tailscale-netmap.service

echo
echo "========================================"
echo " SETUP COMPLETE"
echo "========================================"
echo
echo "Now authenticate Tailscale and advertise the routes:"
echo
echo "sudo tailscale up --advertise-routes=192.168.2.0/24 --advertise-exit-node"
echo
echo "Then approve the advertised route in the Tailscale admin console."
echo