#!/usr/bin/with-contenv bashio
# ==============================================================================
# Start Watchdog service
# ==============================================================================
declare failed_count=0
declare supervisor_state

bashio::log.info "Starting local supervisor watchdog..."

while [[ failed_count -lt 2 ]];
do
    sleep 300
    supervisor_state="$(cat /run/supervisor)"

    if [[ "${supervisor_state}" = "running"  ]]; then

        # Check API
        if bashio::supervisor.ping > /dev/null; then
            failed_count=0
        else
            bashio::log.warning "Maybe found an issue on API healthy"
            ((failed_count++))
        fi

    elif [[  "close stopping" = *"${supervisor_state}"* ]]; then
        bashio::log.warning "Maybe found an issue on shutdown"
        ((failed_count++))
    else
        failed_count=0
    fi

done

bashio::exit.nok "Watchdog detected issue with Supervisor - taking container down!"
