#!/bin/bash
# info: delete firewall chain
# options: CHAIN
#
# example: v-delete-firewall-chain WEB
#
# This function adds new rule to system firewall

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
chain=$(echo $1 | tr '[:lower:]' '[:upper:]')

iptables='/sbin/iptables'
# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# shellcheck source=/usr/local/hestia/func/firewall.sh
source $HESTIA/func/firewall.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '1' "$#" 'CHAIN'
is_format_valid 'chain'
is_system_enabled "$FIREWALL_SYSTEM" 'FIREWALL_SYSTEM'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Self heal iptables links
heal_iptables_links

# Deleting chain
chains=$HESTIA/data/firewall/chains.conf
banlist=$HESTIA/data/firewall/banlist.conf
chain_param=$(grep "CHAIN='$chain'" $chains 2> /dev/null)
if [ -n "$chain_param" ]; then
	parse_object_kv_list "$chain_param"
	sed -i "/CHAIN='$chain'/d" $chains
	sed -i "/CHAIN='$chain'/d" $banlist
	$iptables -D INPUT -p $PROTOCOL \
		--dport $PORT -j fail2ban-$CHAIN 2> /dev/null
fi

# Deleting iptables chain
$iptables -F fail2ban-$CHAIN 2> /dev/null
$iptables -X fail2ban-$CHAIN 2> /dev/null

# Changing permissions
chmod 660 $chains

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit
