#!/bin/bash
# info: stop system firewall
# options: NONE
#
# The function stops  iptables


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Defining absolute path for iptables and modprobe
iptables="/sbin/iptables"
modprobe="/sbin/modprobe"

# Includes
source /etc/profile.d/hestia.sh
source $HESTIA/func/main.sh
source $HESTIA/conf/hestia.conf


#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

#is_system_enabled "$FIREWALL_SYSTEM" 'FIREWALL_SYSTEM'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Creating temporary file
tmp=$(mktemp)

# Flushing INPUT chain
echo "$iptables -P INPUT ACCEPT" >> $tmp
echo "$iptables -F INPUT" >> $tmp

# Deleting hestia chain
echo "$iptables -X hestia" >> $tmp

# Deleting custom chains
chains=$(cat $HESTIA/data/firewall/chains.conf 2>/dev/null)
IFS=$'\n'
for chain in $chains; do
    parse_object_kv_list "$chain"
    echo "$iptables -F fail2ban-$CHAIN" >> $tmp
    echo "$iptables -X fail2ban-$CHAIN" >> $tmp
done

# Applying rules
bash $tmp 2>/dev/null

# Deleting temporary file
rm -f $tmp

# Saving rules to the master iptables file
if [ -d "/etc/sysconfig" ]; then
    /sbin/iptables-save > /etc/sysconfig/iptables
    if [ -z "$(ls /etc/rc3.d/S*iptables 2>/dev/null)" ]; then
        /sbin/chkconfig iptables off
    fi
else
    /sbin/iptables-save > /etc/iptables.rules
    if dpkg-query -W -f'${Status}' "netplan*" 2>/dev/null | grep -q "ok installed"; then
        preup="/usr/lib/networkd-dispatcher/routable.d/50-ifup-hooks"
        if [ ! -e "$preup" ]; then
            IFS='%'
            echo '#!/bin/bash' > $preup
            echo '' >> $preup
            echo 'if [ "$IFACE" == "'$(/bin/ip token | awk -F 'dev ' '{print $2}')'" ]; then' >> $preup
            echo '    sleep 3' >> $preup
            echo '    /sbin/iptables-restore < /etc/iptables.rules' >> $preup
            echo 'fi' >> $preup
            echo "exit 0" >> $preup
            chmod +x $preup
        fi
    else
        preup="/etc/network/if-pre-up.d/iptables"
        if [ ! -e "$preup" ]; then
            echo '#!/bin/sh' > $preup
            echo "/sbin/iptables-restore < /etc/iptables.rules" >> $preup
            echo "exit 0" >> $preup
            chmod +x $preup
        fi
    fi
fi


#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

exit
