#!/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|LTSP-Server|Minimal' ; then
    :
else
    exit 0
fi

server=webcache

# Test ownership of the squid cache directory
if test -d /var/spool/squid ; then
    SQUIDOWNER=$(find /var/spool/squid -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/squid ; then
        echo "success: $0: Binary /usr/sbin/squid is present."
    else
        echo "error: $0: Binary /usr/sbin/squid is missing."
    fi

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

    if egrep -q '^refresh_pattern \(Release\|Package\(.gz\)\*\)$' /etc/squid/squid.conf
    then
        echo "error: $0: squid typo causing APT problem is present (#591839)."
    else
        echo "success: $0: squid 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 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
    (
	http_proxy=$(/usr/share/debian-edu-config/tools/wpad-extract 2>/dev/null || true)
	if [ -n "$http_proxy" ] ; then
	    echo "success: $0: WPAD file '$url' includes 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=https://www.intern/

if HEAD $HEADOPTS $url 2>&1 | grep -q '200 OK' ; 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
