#!/bin/bash
# info: stop service
# options: SERVICE
#
# example: v-stop-service apache2
#
# This function stops system service.

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

# Argument definition
service=$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' "$#" 'SERVICE'
is_format_valid 'service'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

if [ "$service" = "php-fpm" ]; then
	for php_ver in $(multiphp_versions); do
		service_list="${service_list} php${php_ver}-fpm"
	done
else
	service_list="$service"
fi

for service in $service_list; do
	if [ "$service" = "iptables" ]; then
		$BIN/v-stop-firewall
	else
		systemctl stop "$service"
		result=$?
		if [ "$result" -ne 0 ]; then
			$BIN/v-log-action "system" "Error" "System" "Service failed to stop (Name: $service)."
		else
			$BIN/v-log-action "system" "Info" "System" "Service stopped (Name: $service)."
		fi
	fi
	check_result $? "ERROR: $service stop failed" "$E_RESTART"

done

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit
