#!/bin/bash

PORT=25565

function package_exists() {
    return dpkg -l "$1" &> /dev/null
}

echo "Configuring firewall on $PORT"

if ! package_exists ipset ; then
    echo "Configuring ipset..."
    apt-get install ipset -y &> /dev/null
fi

if ! package_exists ipset-persisent ; then
     echo "Installing ipset-persistent"
     apt-get install ipset-persisent -y &> /dev/null
fi

ipset -F tcpshield &> /dev/null
ipset -X tcpshield &> /dev/null
ipset -N tcpshield nethash

for IP in $(curl -q https://www.tcpshield.com/v4/); do
    ipset -A tcpshield $IP
done

for IP in $(curl -q https://www.tcpshield.com/v4-cf/); do
    ipset -A tcpshield $IP
done

ipset -A tcpshield 127.0.0.1 # geyser

iptables -t raw -F
iptables -t raw -A PREROUTING -m set --match-set tcpshield src -p tcp --dport $PORT -j ACCEPT
iptables -t raw -A PREROUTING -p tcp --dport $PORT -j DROP

echo "Your firewall has now been configured to drop outside connections to $PORT. If your server is listening on a different port, please download this script and update as necessary."
