#!/bin/sh

ZIPROXY_TCP_PORT=8080

STATUS_ERROR=1
STATUS_SKIP=77

test_apache() {
    netstat --tcp -lnp | grep apache | 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
}

test_wget() {
    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
}

test_ziproxy() {
    netstat --tcp -lnp | grep ziproxy | grep $ZIPROXY_TCP_PORT

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

test_request_over_ziproxy() {
    MAXTRY=5
    itry=0

    while [ $itry -lt $MAXTRY ]; do
        http_proxy=localhost:$ZIPROXY_TCP_PORT wget -q -O /dev/null \
                  -4 localhost:80 && break

        itry=`expr $itry + 1`
        sleep 1
    done

    if [ "$itry" -eq "$MAXTRY" ]; then
        echo "requests to Ziproxy on port TCP/$ZIPROXY_TCP_PORT failed $MAXTRY times"
        echo "ending $0 with status $STATUS_ERROR"
        exit $STATUS_ERROR
    fi
}

## main
test_apache
test_wget
test_ziproxy
test_request_over_ziproxy

exit 0
