#!/bin/bash
# info: rebuild cron jobs
# options: USER [RESTART]
#
# example: v-rebuild-cron-jobs admin yes
#
# This function rebuilds system cron config file for specified user.

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

# Argument definition
user=$1
restart=$2

# 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 '1' "$#" 'USER [RESTART]'
is_format_valid 'user' 'restart'
is_system_enabled "$CRON_SYSTEM" 'CRON_SYSTEM'
is_object_valid 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Rebuild cron jobs
sync_cron_jobs

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

# Restarting crond
$BIN/v-restart-cron "$restart"
check_result $? "Cron restart failed" > /dev/null
$BIN/v-log-action "system" "Info" "System" "Rebuilt cron jobs (User: $user)."

# Logging
log_event "$OK" "$ARGUMENTS"

exit
