#!/bin/bash
# Script called on module start, as primary, for starting application services

# For logging into module log use:
# "$SAFE/safekit" printi "message"
# "$SAFE/safekit" printe "message"

unset POSIXLY_CORRECT
scriptName=$(basename "$0")
# Import utils functions
source "$SAFEUSERBIN/module_scripts_utils"

# stdout goes into module script log
echo "Running $scriptName $*"

# Array of service names as defined in argument -Services or in SERVICES configuration variable
servicesList=$(Get_ServicesArray --ScriptArgs "$*" --ReverseOrder false)
if [ -z "$servicesList" ]; then
    # No services found
    exit 0
fi
echo "--- Start and check of SERVICES ${servicesList}"
IFS=',' read -r -a servicesArray <<< "$servicesList"
for serviceName in "${servicesArray[@]}"; do
    # Start the service
    if ! Manage_Service -ServiceName "$serviceName" -Action "start" ; then
        "$SAFE/safekit" printe "$scriptName: $serviceName start failed"
        Stop_Module_And_Exit -ScriptName "$scriptName"
    fi

    # Check the service status
    status=$(Check_Service -ServiceName "$serviceName" -Status "active" -Timeout 10)
    if [[ "$status" != "active" && "$status" != "activating" ]]; then
        "$SAFE/safekit" printe "$scriptName: $serviceName not active or activating"
        # Comment to not stop the module when it is not critical
        Stop_Module_And_Exit -ScriptName "$scriptName"
    fi

    # If necessary, uncomment to delay the start of the next service
#   if [[ "$serviceName" != "${servicesArray[-1]}" ]]; then
#      sleep 10
#   fi    
done