#!/bin/sh

# check iptables rule specification is exist,
# if not add it
check_and_add_iptables()
{
    iptables -C "$@" > /dev/null 2>&1
    EXIST=$?
    if [ $EXIST -ne 0 ]; then
        iptables -A "$@"
    fi
}

add_input_tcp_filter() {
    check_and_add_iptables INPUT -p tcp -m tcp --dport "$1" -m comment --comment "$2" -j ACCEPT
}

add_input_udp_filter() {
    check_and_add_iptables INPUT -p udp -m udp --dport "$1" -m comment --comment "$2" -j ACCEPT
}

# allow basic services
add_input_tcp_filter 22 SSH
add_input_tcp_filter 2263 SSH
add_input_tcp_filter 80 HTTP
add_input_tcp_filter 443 HTTPS

# allow TCP
# add_input_tcp_filter 111 Tencent
# add_input_udp_filter 111 Tencent

# allow DNS
# add_input_tcp_filter 53 DNS
# add_input_udp_filter 53 DNS

# allow internal network
check_and_add_iptables INPUT -s 127.0.0.0/24 -m comment --comment "Internal Network" -j ACCEPT
# allow ping
check_and_add_iptables INPUT -p icmp -m comment --comment ping -j ACCEPT
# allow all established and related connections
check_and_add_iptables INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# allow loopback
check_and_add_iptables INPUT -i lo -j ACCEPT
# dropped for INPUT by default
iptables -P INPUT DROP

# allow by default
add_input_tcp_filter 9443 gost-proxy
add_input_tcp_filter 6330 node-exporter

##########
# if you use ufw, please execute `sudo ufw allow xxxx/tcp comment 'xxxx'``
##########

# ====================
