#!/bin/bash
# info: change cron job
# options: USER JOB MIN HOUR DAY MONTH WDAY CRON_COMMAND
#
# example: v-change-cron-job admin 7 * * * * * /usr/bin/uptime
#
# This function is used for changing existing job. It fully replace job
# parameters with new one but with same id.

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

# Argument definition
user=$1
job=$2
min=$3
hour=$4
day=$5
month=$6
wday=$7
cron_command=$8

# 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 '7' "$#" 'USER JOB MIN HOUR DAY MONTH WDAY CRON_COMMAND'
is_format_valid 'user' 'job' 'min' 'hour' 'day' 'month' 'wday' 'cron_command'
is_system_enabled "$CRON_SYSTEM" 'CRON_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'cron' 'JOB' "$job"
is_object_unsuspended 'cron' 'JOB' "$job"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Generating timestamp
time_n_date=$(date +'%T %F')
time=$(echo "$time_n_date" | cut -f 1 -d \ )
date=$(echo "$time_n_date" | cut -f 2 -d \ )

# Concatenating cron string
cron_command=$(echo "$cron_command" | sed -e "s/'/%quote%/g")
str="JOB='$job' MIN='$min' HOUR='$hour' DAY='$day' MONTH='$month' WDAY='$wday'"
str="$str CMD='$cron_command' SUSPENDED='no' TIME='$time' DATE='$date'"

# Deleting old job
sed -i "/JOB='$job' /d" $USER_DATA/cron.conf

# Adding new
echo "$str" >> $USER_DATA/cron.conf

# Sorting jobs by id
sort_cron_jobs

# Sync system cron with user
sync_cron_jobs

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

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

# Logging
$BIN/v-log-action "$user" "Info" "Cron Jobs" "Cron job updated (Job: $job, Command: $cron_command)."
log_event "$OK" "$ARGUMENTS"

exit
