#!/bin/bash
# info: list cron job
# options: USER JOB [FORMAT]
#
# example: v-list-cron-job admin 7
#
# This function of obtaining cron job parameters.

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

# Argument definition
user=$1
job=$2
format=${3-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 function
json_list() {
	echo "{"
	echo -n '    "'$job'": {
        "MIN": "'$MIN'",
        "HOUR": "'$HOUR'",
        "DAY": "'$DAY'",
        "MONTH": "'$MONTH'",
        "WDAY": "'$WDAY'",
        "CMD": "'$CMD'",
        "JOB": "'$JOB'",
        "SUSPENDED": "'$SUSPENDED'",
        "TIME": "'$TIME'",
        "DATE": "'$DATE'"
    }'
	echo
	echo '}'
}

# SHELL list function
shell_list() {
	echo "MINUTE:         $MIN"
	echo "HOUR:           $HOUR"
	echo "DAY:            $DAY"
	echo "MONTH:          $MONTH"
	echo "DAY OF WEEK:    $WDAY"
	echo "COMMAND:        $CMD"
	echo "SUSPENDED:      $SUSPENDED"
	echo "TIME:           $TIME"
	echo "DATE:           $DATE"
}

# PLAIN list function
plain_list() {
	echo -e "$MIN\t$HOUR\t$DAY\t$MONTH\t$WDAY\t$CMD\t$SUSPENDED\t$TIME\t$DATE"
}

# CSV list function
csv_list() {
	echo "MIN,HOUR,DAY,MONTH,WDAY,CMD,SUSPENDED,TIME,DATE"
	echo "$MIN,$HOUR,$DAY,$MONTH,$WDAY,\"$CMD\",$SUSPENDED,$TIME,$DATE'"
}

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

check_args '2' "$#" 'USER JOB [FORMAT]'
is_format_valid 'user'
is_number_format_valid "$job" "job_id"
is_object_valid 'user' 'USER' "$user"

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

# Defining config
conf=$USER_DATA/cron.conf

# Checking job id
cron_line=$(grep "JOB='$job'" $conf)
if [ -z "$cron_line" ]; then
	check_result "$E_NOTEXIST" "cron job $job doesn't exist"
fi

# Parsing cron job
parse_object_kv_list "$cron_line"

# Replacing quoted and backslahed text
CMD=$(echo "$CMD" | sed -e 's/"/\\"/g' -e "s/%quote%/'/g")

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

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

exit
