#!/usr/bin/env bash
# Restore outbound internet for LXD containers (common Docker + LXD conflict on Ubuntu).
set -euo pipefail

if [[ "${EUID}" -ne 0 ]]; then
    echo "Run with sudo: sudo $0" >&2
    exit 1
fi

LXD_BRIDGE="${LXD_BRIDGE:-lxdbr0}"
LXD_SUBNET="$(lxc network get "${LXD_BRIDGE}" ipv4.address 2>/dev/null | cut -d/ -f1 | awk -F. '{print $1"."$2"."$3".0/24"}')"
if [[ -z "${LXD_SUBNET}" || "${LXD_SUBNET}" == ".0/24" ]]; then
    LXD_SUBNET="10.239.141.0/24"
fi

echo "LXD bridge: ${LXD_BRIDGE}"
echo "LXD subnet: ${LXD_SUBNET}"

echo "==> Allow LXD traffic through Docker's DOCKER-USER chain (if present)"
if iptables -L DOCKER-USER -n &>/dev/null; then
    iptables -C DOCKER-USER -i "${LXD_BRIDGE}" -j ACCEPT 2>/dev/null \
        || iptables -I DOCKER-USER 1 -i "${LXD_BRIDGE}" -j ACCEPT
    iptables -C DOCKER-USER -o "${LXD_BRIDGE}" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 2>/dev/null \
        || iptables -I DOCKER-USER 2 -o "${LXD_BRIDGE}" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
    echo "    DOCKER-USER rules added"
else
    echo "    No DOCKER-USER chain (Docker may not be managing iptables)"
fi

echo "==> Ensure FORWARD accepts ${LXD_BRIDGE}"
iptables -C FORWARD -i "${LXD_BRIDGE}" -j ACCEPT 2>/dev/null \
    || iptables -I FORWARD 1 -i "${LXD_BRIDGE}" -j ACCEPT
iptables -C FORWARD -o "${LXD_BRIDGE}" -j ACCEPT 2>/dev/null \
    || iptables -I FORWARD 1 -o "${LXD_BRIDGE}" -j ACCEPT

echo "==> Ensure MASQUERADE for ${LXD_SUBNET}"
if ! iptables -t nat -C POSTROUTING -s "${LXD_SUBNET}" ! -d "${LXD_SUBNET}" -j MASQUERADE 2>/dev/null; then
    iptables -t nat -A POSTROUTING -s "${LXD_SUBNET}" ! -d "${LXD_SUBNET}" -j MASQUERADE
fi

echo "==> LXD network: disable per-network firewall, refresh NAT"
lxc network set "${LXD_BRIDGE}" ipv4.firewall false
lxc network set "${LXD_BRIDGE}" ipv6.firewall false
lxc network set "${LXD_BRIDGE}" ipv4.nat false
lxc network set "${LXD_BRIDGE}" ipv4.nat true

echo "==> Restart LXD daemon"
if command -v snap >/dev/null 2>&1 && snap list lxd &>/dev/null; then
    snap restart lxd
else
    systemctl restart lxd || systemctl restart snap.lxd.daemon
fi
sleep 2

echo "==> Smoke test (ephemeral container in project snapcraft)"
TEST_NAME="lxd-net-test-$$"
lxc launch ubuntu:26.04 "${TEST_NAME}" --project snapcraft
trap 'lxc delete -f --project snapcraft "${TEST_NAME}" 2>/dev/null || true' EXIT
if lxc exec --project snapcraft "${TEST_NAME}" -- curl -fsSI --max-time 15 https://github.com | head -1; then
    echo "OK: container outbound HTTPS works"
else
    echo "FAIL: container still cannot reach github.com" >&2
    echo "Consider permanent Docker fix: add \"iptables\": false to /etc/docker/daemon.json and restart docker" >&2
    exit 1
fi

echo ""
echo "Done. LXD containers should have outbound internet now."
