#!/bin/bash
# info: restart backend server
# options: NONE
#
# The function reloads backend server configuration.


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Includes
source $HESTIA/func/main.sh
source $HESTIA/conf/hestia.conf
PATH="$PATH:/usr/local/sbin:/sbin:/usr/sbin:/root/bin"

send_email_report() {
    email=$(grep CONTACT $HESTIA/data/users/admin/user.conf)
    email=$(echo "$email" | cut -f 2 -d "'")
    subj="$(hostname): $WEB_BACKEND restart failed"
    cat $tmpfile |$SENDMAIL -s "$subj" $email
    [[ -f "$tmpfile" ]] && rm -f $tmpfile
}


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

# Exit
if [ "$1" = "no" ]; then
    exit
fi

# Schedule restart
if [ "$1" = 'scheduled' ] || [ -z "$1" -a "$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 [ -z "$WEB_BACKEND" ] || [ "$WEB_BACKEND" = 'remote' ]; then
    exit
fi

tmpfile=$(mktemp)
for php_folder in /etc/php/*; do
    [ ! -d "${php_folder}/fpm/pool.d/" ] && continue

    v_php="$(basename $php_folder)"
    v_phpfpm="php${v_php}-fpm"

    if [ ! -f "/etc/php/${v_php}/fpm/pool.d/dummy.conf" ]; then
        cp -f "$HESTIA_INSTALL_DIR/php-fpm/dummy.conf" "/etc/php/${v_php}/fpm/pool.d/"
        sed -i "s/9999/99${v_php//.}/g" "/etc/php/${v_php}/fpm/pool.d/dummy.conf"
    fi

    $BIN/v-restart-service "$v_phpfpm" >> $tmpfile 2>&1
    if [ $? -ne 0 ]; then
        send_email_report
        check_result $E_RESTART "$v_phpfpm restart failed"
    fi
done

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


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

[[ -f "$tmpfile" ]] && rm -f $tmpfile
exit
