#update core packages
apt update && apt upgrade -y

#apply all the packages I need
apt install -y ca-certificates curl ethtool iptables-persistent git htop

#Enable IP Forwarding (Persistent)
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
grep -qF "net.ipv4.ip_forward=1" /etc/sysctl.conf || echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

# Add the "Catch-All" NAT rule for eth0
# "If traffic leaves eth0, masquerade it (make it look like the LXC's IP)"
# This works for ANY internal Docker subnet (172.x, 192.x, 10.x)
iptables -C POSTROUTING -t nat -o eth0 -j MASQUERADE 2>/dev/null || \
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# Save the rules (Requires iptables-persistent / netfilter-persistent installed)
netfilter-persistent save

#change the virtio settings and Apply checksum fix immediately
if ! grep -q "post-up /sbin/ethtool" /etc/network/interfaces; then
    sed -i '/gateway/a \        post-up /sbin/ethtool -K eth0 tx off rx off' /etc/network/interfaces
fi
ethtool -K eth0 tx off rx off

#Enable Root SSH Login
sed -i 's/^#*PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
grep -q "^PermitRootLogin yes" /etc/ssh/sshd_config || echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
systemctl restart ssh

#install the keyring for the docker repo
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc

# Add the repository to Apt sources:
tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/debian
Suites: $(. /etc/os-release && echo "$VERSION_CODENAME")
Components: stable
Signed-By: /etc/apt/keyrings/docker.asc
EOF

#update from the docker repo and install docker
apt update && apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y

#pre-empt that pesky json is a folder issue
rm -rf /root/.docker/config.json
mkdir -p /root/.docker
echo "{}" > /root/.docker/config.json 

#sanitize the LXC  
systemctl stop docker
rm -f /etc/docker/key.json
rm -f /etc/ssh/ssh_host_*
truncate -s 0 /etc/machine-id
rm -f /var/lib/dbus/machine-id
ln -s /etc/machine-id /var/lib/dbus/machine-id

#Clean Apt Cache & Logs
apt clean
rm -rf /var/lib/apt/lists/*
rm -rf /var/log/*.log
rm -rf /var/log/journal/*

#Clear Command History
history -c && history -w

#shutdown and convert to template
shutdown now