#!/bin/sh

QM=/usr/sbin/qm

[ -x ${QM} ] || {
    echo "${QM} not executable for us"
    exit 1
}

exitcode=0

allvms() {
    $QM list | grep running | awk ' { print $1 } '
}

hasagent() {
    VM=$1
    $QM config ${VM} -current 1 | grep -q 'agent: 1'
    [ $? -eq 0 ] && echo 'yes' || echo 'no'
}

pingagent() {
    VM=$1
    ERR=$($QM agent ${VM} ping 2>&1)
    [ -z "$ERR" ] && echo 'ok' || echo "${ERR}"
}

for vm in `allvms`; do
    AGENT=$(hasagent $vm)

    if [ "${AGENT}" = "yes" ]; then
        OK=$(pingagent $vm)
        if [ "${OK}" = "ok" ]; then
            echo "VM ${vm} pinged back"
        else
            echo "Issue with ${vm}: ${OK}"
            exitcode=1
        fi
    fi
done

exit $exitcode
