#!/bin/bash
#---------------------
# Testing masakari-daemons
#---------------------
set -e
DAEMONS=('masakari-host-monitor'
         'masakari-instance-monitor'
         'masakari-introspective-instance-monitor'
         'masakari-process-monitor')

ret=0

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

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

for daemon in "${DAEMONS[@]}"; do
    timeout_loop "systemctl restart $daemon"
    if [ "$ret" -eq 1 ]; then
        systemctl status $daemon
        journalctl -x --no-pager -u $daemon
    fi
    timeout_loop "systemctl is-active $daemon"
    if [ "$ret" -eq 1 ]; then
        systemctl status $daemon
        journalctl -x --no-pager -u $daemon
    fi
done

exit $ret
