#!/usr/bin/env bash
# @(#) check component readiness until all components are ready or timeout

# Use the unofficial bash strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail; export FS=$'\n\t'

function component_healthy {
    HEALTH=$(docker compose ps ${1} --format json | jq .Health)
    if [[ "$HEALTH" != '"healthy"' ]]; then
        echo 1 # = false
    else
        echo 0 # = true
    fi
}

function curl_apache {
    curl --fail -k -L --max-redirs 5 --silent --output /dev/null --head ${DEPLOY_BASE_URL}
    echo $?
}

function cmem_is_ready {

    # Check health of CMEM components
    if [[ "$(component_healthy keycloak)" == "0" ]] &&
       [[ "$(component_healthy apache2)" == "0" ]] &&
       [[ "$(component_healthy explore)" == "0" ]] &&
       [[ "$(component_healthy dataintegration)" == "0" ]] ;
    then
        echo 0 # = true
    else
        echo 1 # = false
    fi
}

function wait_until_cmem_is_ready {
    GREEN="\033[0;32m"
    RED="\033[0;31m"
    NC="\033[0m" # No Color

    MAX_CHECKS=100
    SLEEP_BETWEEN_CHECKS=2
    COUNT_CHECKS=1

    echo -n "Waiting for healthy orchestration"
    until [[ "$(cmem_is_ready)" == "0" ]] || [[ "${COUNT_CHECKS}" -gt "${MAX_CHECKS}" ]] ; do
        printf '.'
        sleep ${SLEEP_BETWEEN_CHECKS}
        COUNT_CHECKS=$((COUNT_CHECKS+1))
    done
    if [[ "$(cmem_is_ready ${1:-})" == "0" ]];
    then
        echo -e " ${GREEN}done${NC}"
    else
        echo -e " ${RED}timeout or failed (please check logs and/or check container state with 'docker ps')${NC}"
        exit 1
    fi
}

wait_until_cmem_is_ready
