#!/bin/bash
# info: delete cron job
# options: USER JOB
#
# example: v-delete-cron-job admin 9
#
# This function deletes cron job.

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

# Argument definition
user=$1
job=$2
restart=$3

# 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"

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

check_args '2' "$#" 'USER JOB [RESTART]'
is_format_valid 'user' 'job' 'restart'
is_system_enabled "$CRON_SYSTEM" 'CRON_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'cron' 'JOB' "$job"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

suspended=$(grep "JOB='$job'" $USER_DATA/cron.conf | grep "SUSPENDED='yes'")
# Deleting job
sed -i "/JOB='$job' /d" $USER_DATA/cron.conf

# Sorting jobs by id
sort_cron_jobs

# Sync system cron with user
sync_cron_jobs

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

# Decreasing cron value
decrease_user_value "$user" '$U_CRON_JOBS'

# Check if is suspended to decrease the suspended value
if [ -n "$suspended" ]; then
	decrease_user_value "$user" '$SUSPENDED_CRON'
fi

# Restarting cron
$BIN/v-restart-cron "$restart"
check_result $? "Restart restart failed" > /dev/null

# Logging
$BIN/v-log-action "$user" "Info" "Cron Jobs" "Cron job deleted (ID: $job)."
log_event "$OK" "$ARGUMENTS"

exit
