#!/bin/bash
# info: list firewall rule
# options: RULE [FORMAT]
#
# example: v-list-firewall-rule 2
#
# This function of obtaining firewall rule parameters.

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

# Argument definition
rule=$1
format=${2-shell}

# 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
# load config file
source_conf "$HESTIA/conf/hestia.conf"

json_list() {
	echo '{'
	echo '    "'$RULE'": {
        "ACTION": "'$ACTION'",
        "PROTOCOL": "'$PROTOCOL'",
        "PORT": "'$PORT'",
        "IP": "'$IP'",
        "COMMENT": "'$COMMENT'",
        "SUSPENDED": "'$SUSPENDED'",
        "TIME": "'$TIME'",
        "DATE": "'$DATE'"
    }'
	echo '}'
}

# SHELL list function
shell_list() {
	echo "ACTION:         $ACTION"
	echo "PROTOCOL:       $PROTOCOL"
	echo "PORT:           $PORT"
	echo "IP:             $IP"
	echo "COMMENT:        $COMMENT"
	echo "SUSPENDED:      $SUSPENDED"
	echo "TIME:           $TIME"
	echo "DATE:           $DATE"
}

# PLAIN list function
plain_list() {
	echo -ne "$RULE\t$ACTION\t$PROTOCOL\t$PORT\t$IP\t$COMMENT\t"
	echo -e "$SUSPENDED\t$TIME\t$DATE"
}

# CSV list function
csv_list() {
	echo "RULE,ACTION,PROTOCOL,PORT,IP,COMMENT,SUSPENDED,TIME,DATE"
	echo "$RULE,$ACTION,$PROTOCOL,$PORT,$IP,$COMMENT,$SUSPENDED,$TIME,$DATE"
}

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

check_args '1' "$#" 'RULE [FORMAT]'
is_number_format_valid "$rule" "rule id"
is_object_valid '../../../data/firewall/rules' 'RULE' "$rule"

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

# Parsing rules
parse_object_kv_list $(grep "RULE='$rule'" $HESTIA/data/firewall/rules.conf)

# Listing data
case $format in
	json) json_list ;;
	plain) plain_list ;;
	csv) csv_list ;;
	shell) shell_list ;;
esac

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

exit
