#!/bin/bash
# info: start service
# options: SERVICE
#
# example: v-start-service mysql
#
# This function starts 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'

#----------------------------------------------------------#
#                       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
		if [ -f /etc/redhat-release ]; then
			RES=$(systemctl is-enabled nftables | grep enabled)
			if [ -z "$RES" ]; then
				systemctl enable nftables --now
			fi
			systemctl status nftables
			if [ $? -ne 0 ]; then
				systemctl start nftables
			fi
		fi
		$BIN/v-update-firewall
	else
		systemctl start "$service"
		result=$?
		if [ "$result" -ne 0 ]; then
			$BIN/v-log-action "system" "Error" "System" "Service failed to start (Name: $service)."
		else
			$BIN/v-log-action "system" "Info" "System" "Service started (Name: $service)."
		fi
	fi
	check_result $? "ERROR: $service start failed" "$E_RESTART"
done

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit