#!/bin/bash

# This script checks ALL services on the server and returns a status for each.

# Return format is simple ENV with the following format:
# SERVICE_NAME_HEALTH=healthy|unhealthy|unknown
# SERVICE_NAME_PORTS=port1,port2,port3

# Get all services on the server
SCRIPT_DIR="$(dirname "$0")"

# // DROPSHELL_DIR
# //   |-- backups
# //   |-- services
# //       |-- service name
# //           |-- config  <-- this is passed as argument to all scripts
# //               |-- service.env
# //               |-- (user config files)
# //           |-- template
# //               |-- (script files)

# Get all services on the server
SERVICES_PATH="${SCRIPT_DIR}/../../"

# Get all service names
SERVICE_NAMES=$(ls "${SERVICES_PATH}")

# Iterate over all service names
for SERVICE_NAME in ${SERVICE_NAMES}; do
    # Get the service health
    SERVICE_PATH="${SERVICES_PATH}/${SERVICE_NAME}"
    STATUS_FILE="${SERVICE_PATH}/template/status.sh"
    if [ -f "${STATUS_FILE}" ]; then
        # suppress all output from the status script
        if $(bash "${STATUS_FILE}" "${SERVICE_PATH}/config" > /dev/null 2>&1); then
            SERVICE_HEALTH="healthy"
        else
            SERVICE_HEALTH="unhealthy"
        fi
    else
        SERVICE_HEALTH="unknown"
    fi

    # Get the service ports
    PORTS_FILE="${SERVICE_PATH}/template/ports.sh"
    if [ -f "${PORTS_FILE}" ]; then
        # capture output from the ports script
        SERVICE_PORTS=$(bash "${PORTS_FILE}" "${SERVICE_PATH}/config" 2>&1)
    else
        SERVICE_PORTS=""
    fi

    # return the health and ports
    echo "${SERVICE_NAME}_HEALTH=${SERVICE_HEALTH}"
    echo "${SERVICE_NAME}_PORTS=${SERVICE_PORTS}"
done