#!/bin/bash

echo "Setting up firewall rules..."

# Reset existing rules
sudo iptables -F
sudo ip6tables -F

# Set default policies to DROP (more secure)
sudo iptables -P INPUT DROP
sudo ip6tables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo ip6tables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
sudo ip6tables -P OUTPUT ACCEPT

# Allow established and related connections (IPv4 & IPv6)
sudo iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo ip6tables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# Allow loopback interface (IPv4 & IPv6)
sudo iptables -A INPUT -i lo -j ACCEPT
sudo ip6tables -A INPUT -i lo -j ACCEPT

# Allow ICMP (ping requests) (IPv4 & IPv6)
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

# Allow SSH (IPv4)
sudo iptables -A INPUT -p tcp -s 10.0.0.2 -j ACCEPT
sudo iptables -A INPUT -p tcp -s 10.0.0.3 -j ACCEPT
sudo iptables -A INPUT -p tcp -s 10.0.0.4 -j ACCEPT
sudo iptables -A INPUT -p tcp -s 10.0.0.5 -j ACCEPT
sudo iptables -A INPUT -p tcp -s 10.0.0.9 --dport 22 -j ACCEPT

# Deny local index page connection
sudo iptables -A INPUT -p tcp -s 10.0.0.9 --dport 80 -j DROP

# Allow UDP traffic on port 51820 (WireGuard VPN)
sudo iptables -A INPUT -p udp --dport 51820 -j ACCEPT

# Allow HTTP and HTTPS traffic (IPv4 & IPv6)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow custom ports (IPv4 & IPv6)
## Palworld
#sudo iptables -A INPUT -p udp --dport 8211 -j ACCEPT
## Terraria
#sudo iptables -A INPUT -p tcp --dport 7777 -j ACCEPT
## Valheim
sudo iptables -A INPUT -p udp --dport 2456 -j ACCEPT

## ARK
sudo iptables -A INPUT -p udp --dport 27015 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 27015 -j ACCEPT
sudo iptables -A INPUT -p udp --dport 7777 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 7777 -j ACCEPT

# Drop all remaining traffic (IPv4 & IPv6)
sudo iptables -A INPUT -j DROP
sudo ip6tables -A INPUT -j DROP

# Restart docker so it can apply it's rules
sudo systemctl restart docker

sudo netfilter-persistent save

echo "Firewall rules successfully applied!"
