#!/bin/bash
# info: restart cron service
# options: NONE
#
# example: v-restart-cron
#
# This function tells crond service to reread its configuration files.

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

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

send_email_report() {
	email=$(grep CONTACT $HESTIA/data/users/admin/user.conf)
	email=$(echo "$email" | cut -f 2 -d "'")
	tmpfile=$(mktemp)
	subj="$(hostname): $CRON_SYSTEM restart failed"
	systemctl status "$CRON_SYSTEM" >> $tmpfile 2>&1
	service "$CRON_SYSTEM" restart >> $tmpfile 2>&1
	cat $tmpfile | $SENDMAIL -s "$subj" $email
	rm -f $tmpfile
}

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

# Exit
if [ -z "$CRON_SYSTEM" ] || [ "$CRON_SYSTEM" = 'remote' ]; then
	exit
fi

# Schedule restart
if [ "$1" = 'scheduled' ] || [ -z "$1" ] && [ "$SCHEDULED_RESTART" = 'yes' ]; then
	sed -i "/\/$SCRIPT now/d" $HESTIA/data/queue/restart.pipe
	echo "$BIN/$SCRIPT now" >> $HESTIA/data/queue/restart.pipe
	exit
fi

if [ "$1" = "no" ] || [ -z "$1" ]; then
	exit
fi

# Restart system
$BIN/v-restart-service $CRON_SYSTEM > /dev/null 2>&1
if [ $? -ne 0 ]; then
	send_email_report
	check_result "$E_RESTART" "$CRON_SYSTEM restart failed"
fi

# Update restart queue
if [ -e "$HESTIA/data/queue/restart.pipe" ]; then
	sed -i "/\/$SCRIPT now/d" $HESTIA/data/queue/restart.pipe
fi

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

exit
