#!/bin/bash
# info: update system queue
# options: PIPE
#
# example: v-update-sys-queue
#
# This function is responsible queue processing. Restarts of services,
# scheduled backups, web log parsing and other heavy resource consuming
# operations are handled by this script. It helps to optimize system behaviour.
# In a nutshell Apache will be restarted only once even if 10 domains are
# added or deleted.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#
# Argument definition
queue=$1

# 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' "$#" 'QUEUE'

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

b_task=$(ps auxf | grep -v "grep" | grep "$BIN/v-update-sys-queue backup")
b_task=$(echo "$b_task" | grep -v sudo | wc -l)
d_task=$(ps auxf | grep -v "grep" | grep "$BIN/v-update-sys-queue dns")
d_task=$(echo "$d_task" | grep -v sudo | wc -l)
if [ "$b_task" -gt 2 ] || [ "$d_task" -gt 2 ]; then
	exit
fi

# Defining pipe functions
case $queue in
	restart) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	webstats) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	backup) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	disk) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	daily) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	traffic) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	dns-cluster) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	letsencrypt) bash $HESTIA/data/queue/$queue.pipe > /dev/null 2>&1 ;;
	*) check_args '1' '0' 'QUEUE' ;;
esac

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

exit
