#!/bin/sh

# Functions test_apache(), test_wget() and test_ziproxy() were copied from
# the validation script of the ziproxy package

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_proxycheck() {
    # Reach port 80 through Ziproxy and expect response containing
    # string "HTTP" from Apache web server.
    proxycheck -d localhost:80 -c chat::"HTTP" localhost:$ZIPROXY_TCP_PORT -aaaaa

    # Proxycheck should terminate with status 100 when the expected string
    # is received, which means an open proxy was detected.
    if [ "$?" != 100 ]; then
        echo "Proxycheck failed to find proxy at localhost:$ZIPROXY_TCP_PORT"
        echo "ending $0 with status $STATUS_ERROR"
        exit $STATUS_ERROR
    fi
}

## main
test_apache
test_wget
test_ziproxy
test_proxycheck

exit 0
