#!/bin/sh

# not used `set -e' because some commands can fail

STATUS_ERROR=1
STATUS_SKIP=77

check_apache() {
    netstat --tcp -ln | grep 80

    if [ "$?" != 0 ]; then
        echo "apache2 is not listening at port TCP/80"
        echo "ending $0 with status $STATUS_SKIP"
        exit $STATUS_SKIP
    fi
}

check_wget_request() {
    wget -q -O /dev/null -4 localhost:80

    if [ "$?" != 0 ]; then
        echo "wget on localhost:80 failed"
        echo "ending $0 with status $STATUS_SKIP"
        exit $STATUS_SKIP
    fi
}

run_wbox() {
    MAXTRY=5
    itry=0

    while [ $itry -lt $MAXTRY ]; do
        wbox localhost 1 | grep "1 replies received" && break
        itry=`expr $itry + 1`

        sleep 1
    done

    if [ "$itry" -eq "$MAXTRY" ]; then
        echo "wbox query on localhost:80 failed $MAXTRY times"
        echo "ending $0 with status $STATUS_ERROR"
        exit $STATUS_ERROR
    fi
}

## main
check_apache
check_wget_request
run_wbox

exit 0
