#!/bin/sh -e
#
# Test if the proxy server (squid) works.

if test -r /etc/debian-edu/config ; then
    . /etc/debian-edu/config
fi

# Only networked profiles use squid
if echo "$PROFILE" | egrep -q 'Main-Server|Workstation|Roaming-Workstation|Thin-Client-Server|Minimal' ; then
    :
else
    exit 0
fi

server=webcache

# Test ownership of the squid cache directory
if test -d /var/spool/squid3 ; then 
    SQUIDOWNER=$(find /var/spool/squid3 -maxdepth 0 -printf %u)
    if [ "$SQUIDOWNER" = "proxy" ] ;  then 
        echo "success: $0: SquidOwner is $SQUIDOWNER"
    else
        echo "error: $0: SquidOwner is $SQUIDOWNER"
        RESULT=1
    fi
fi

# Test if HTTP proxy cache is reachable
if ping -c1 $server > /dev/null 2>&1 ; then
    echo "success: $0: Host '$server' is pingable."
else
    echo "error: $0: Host '$server' is not pingable."
    RESULT=1
fi

# Wait for 10 seconds
HEADOPTS="-t 10"

if echo "$PROFILE" | egrep -q 'Main-Server' ; then
    # Test that the binary exist
    if test -x /usr/sbin/squid3 ; then
        echo "success: $0: Binary /usr/sbin/squid3 is present."
    else
        echo "error: $0: Binary /usr/sbin/squid3 is missing."
    fi

    if pidof squid3 > /dev/null ; then
        echo "success: $0: squid3 is running."
    else
        echo "error: $0: squid3 is not running."
        exit 1
    fi

    if egrep -q '^refresh_pattern \(Release\|Package\(.gz\)\*\)$' /etc/squid3/squid.conf
    then
        echo "error: $0: squid3 typo causing APT problem is present (#591839)."
    else
        echo "success: $0: squid3 typo causing APT problem is not present (#591839)."
    fi
fi

# Verify that the automatic proxy configuration file is available
url=http://wpad/wpad.dat
if /usr/bin/HEAD $HEADOPTS $url > /dev/null 2>&1 ; then
    echo "success: $0: WPAD file is available from '$url'."

    # Subshell to avoid leaking http_proxy and ftp_proxy variables to
    # the rest of this script
    (
	eval `/usr/share/debian-edu-config/tools/wpad-extract`
	if [ "$http_proxy" ] ; then
	    echo "success: $0: WPAD file '$url' include HTTP proxy info."
	else
	    echo "error: $0: WPAD file '$url' is missing HTTP proxy info. (#644373?)"
	fi
    )
else
    echo "error: $0: WPAD file is not available from '$url'."
fi

# Use the proxy
http_proxy=http://$server:3128/
ftp_proxy=$http_proxy
export http_proxy ftp_proxy

url=http://www.intern/

if /usr/bin/HEAD $HEADOPTS $url > /dev/null 2>&1 ; then
    echo "success: $0: Valid response from '$url' using proxy '$http_proxy'."
else
    echo "error: $0: Unable to connect to '$url' using proxy '$http_proxy'."
fi
