#!/bin/bash

source /usr/local/ntlm-auth-api/containers/systemd-service

name=ntlm-auth-api
pid=$$

conf_dir="/usr/local/ntlm-auth-api/var/conf/"
cd $conf_dir || exit 1
env_files=$(ls *.env 2>/dev/null)

# maximum allowed attempts, will be reduced to 5 once passed health check.
max_failures=30
failures=0

while true; do
    check_passed=1

    for env_file in $env_files; do
        full_path="$conf_dir$env_file"
        iden=$(echo $env_file | awk -F '.' '{print $1}')

        host=$(cat $full_path | grep 'HOST' | awk -F '=' '{print $2}')
        port=$(cat $full_path | grep 'LISTEN' | awk -F '=' '{print $2}')

        curl_err=$(mktemp)
        res=$(curl -X GET --silent --show-error http://"$host:$port"/ping 2>"$curl_err")
        curl_exit=$?

        if [ $max_failures -gt 5 ]; then
            echo -n "Checking sub service for domain [$iden]: http://$host:$port/ping, response = [$res]. "
            if [ "$res" != "pong" ]; then
                check_passed=0
                if [ $curl_exit -ne 0 ] && [ -s "$curl_err" ]; then
                    echo -n "Curl error: $(cat "$curl_err"). "
                fi
                echo "Not ready. Skipped checking for other domains."
                rm -f "$curl_err"
                break
            else
                echo "Ready."
            fi
        else
            if [ "$res" != "pong" ]; then
                check_passed=0
                echo -n "Checking sub service for domain [$iden]: http://$host:$port/ping, response = [$res]. "
                if [ $curl_exit -ne 0 ] && [ -s "$curl_err" ]; then
                    echo -n "Curl error: $(cat "$curl_err"). "
                fi
                echo "Not ready. Skipped checking for other domains."
                rm -f "$curl_err"
                break
            fi
        fi
        rm -f "$curl_err"
    done

    if [ $check_passed -eq 0 ]; then
        failures=$((failures + 1))
        if [ $failures -gt $max_failures ]; then
            echo "Maximum service check time exceeded. Service not ready. Please check logs during start up for sub service failures."
            echo '' >/usr/local/ntlm-auth-api/var/run/ntlm-auth-api.pid
            exit 1
        fi
        sleep 1
    else
        echo "$pid" >/usr/local/ntlm-auth-api/var/run/ntlm-auth-api.pid
        max_failures=5
        failures=0
        sleep 10
    fi
done
