#!/bin/bash
# info: delete firewall rule
# options: RULE
#
# example: v-delete-firewall-rule SSH_BLOCK
#
# This function deletes firewall rule.

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

# Argument definition
rule=$1

# Includes
# shellcheck source=/etc/tuliocp/tulio.conf
source /etc/tuliocp/tulio.conf
# shellcheck source=/usr/local/tulio/func/main.sh
source $TULIO/func/main.sh
# load config file
source_conf "$TULIO/conf/tulio.conf"

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

check_args '1' "$#" 'RULE'
is_format_valid 'rule'
is_system_enabled "$FIREWALL_SYSTEM" 'FIREWALL_SYSTEM'
is_object_valid '../../../data/firewall/rules' 'RULE' "$rule"

# Perform verification if read-only mode is enabled
check_tulio_demo_mode

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

# Deleting rule
sed -i "/RULE='$rule' /d" $TULIO/data/firewall/rules.conf

# Reorder firewall rules
rulesf="$TULIO/data/firewall/rules.conf"

if [[ ! -f "$rulesf" ]]; then
	echo "Error: $rulesf not found" >&2
	exit 1
fi

if [[ ! -s "$rulesf" ]]; then
	# Empty file, nothing to reorder
	exit 0
fi

rules_tmp="$(mktemp "${rulesf}.XXXXXX")"
trap 'rm -f "$rules_tmp"' EXIT

# Sort by rule number (field 2, quote-delimited) and renumber sequentially
sort -n -k 2 -t \' "$rulesf" \
	| awk -v q="'" '{ n++; sub("RULE=" q "[0-9]+" q, "RULE=" q n q); print }' \
		> "$rules_tmp"

mv "$rules_tmp" "$rulesf"

# Updating system firewall
$BIN/v-update-firewall

#----------------------------------------------------------#
#                       Tulio                             #
#----------------------------------------------------------#

# Logging
$BIN/v-log-action "system" "Info" "Firewall" "Removed firewall rule (ID: $rule)."
log_event "$OK" "$ARGUMENTS"

exit
