#!/bin/bash
#---------------------
# Testing panko-daemons
#---------------------
set -e
DAEMONS=('apache2')

for daemon in "${DAEMONS[@]}"; do
    systemctl stop $daemon
done

ret=0

timeout_loop () {
    TIMEOUT=50
    while [ "$TIMEOUT" -gt 0 ]; do
        if $1 > /dev/null 2>&1; then
            echo "OK"
            break
        fi
        TIMEOUT=$((TIMEOUT - 1))
        sleep 0.1
    done

    if [ "$TIMEOUT" -le 0 ]; then
        echo "ERROR: $1 FAILED"
        ret=1
    fi
}

for daemon in "${DAEMONS[@]}"; do
    systemctl start $daemon
    timeout_loop "systemctl is-active $daemon"
done

timeout_loop "curl --fail http://localhost:8779"
if [ "$ret" -eq 1 ]; then
    # Run curl one more time without --fail to ensure no silent failures
    curl http://localhost:8779
fi
exit $ret
