#!/bin/bash
# Script called on module stop for stopping application services

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

# ----------------------------------------------------------
# 2 stop modes:
# - graceful stop
#   call standard service stop
# - force stop ($1 == "force")
#   optionally kill application's processes
# ----------------------------------------------------------

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

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

gracefulStop=true
if [ "$1" == "force" ]; then
    gracefulStop=false
fi

# Array of service names as defined in argument -Services or in SERVICES configuration variable
# Reverse order for the stop
servicesList=$(Get_ServicesArray --ScriptArgs "$*" --ReverseOrder true)
if [ -z "$servicesList" ]; then
    # No services found
    exit 0
fi
IFS=',' read -r -a servicesArray <<< "$servicesList"

if $gracefulStop; then
    echo "--- Stop and check of SERVICES ${servicesList}"
    for serviceName in "${servicesArray[@]}"; do
        # Graceful stop
        # Stop the service
        if ! Manage_Service -ServiceName "$serviceName" -Action "stop"; then
            "$SAFE/safekit" printe "$scriptName: $serviceName stop failed"
        fi
        # Check the service status
        status=$(Check_Service -ServiceName "$serviceName" -Status "inactive")
        if [ "$status" != "inactive" ] && [ "$status" != "failed" ] ; then
            "$SAFE/safekit" printe "$scriptName: $serviceName not inactive"
        fi
        # If necessary, uncomment to delay the stop of the next service
#       if [[ "$serviceName" != "${servicesArray[-1]}" ]]; then
#           sleep 10
#       fi 
    done
else
    # Force stop
    # If necessary, insert here command to force the stop

    echo "--- Check of SERVICES ${servicesList}"
    for serviceName in "${servicesArray[@]}"; do
        # Check the service status
        status=$(Check_Service -ServiceName "$serviceName" -Status "inactive")
        if [ "$status" != "inactive" ] && [ "$status" != "failed" ] ; then
            "$SAFE/safekit" printe "$scriptName: $serviceName not inactive"
        fi
    done
fi