#!/bin/sh

interface=
pac=
wpad_domain=

case "$2" in
    up)
	NRCONS=$(nmcli -t --fields UUID con status | wc -l)
	if [ "$NRCONS" = "1" ]; then
	    pac="$DHCP4_WPAD";
	    wpad_domain="DHCP4_DOMAIN_NAME"
	    interface="$1"
	else
	    disableproxy=1
	fi
	;;
    vpn-up)
	if [ "$VPN_IP4_NUM_ROUTES" = "0" ]; then
	    wpad_domain=$(nmcli -t --fields ipv4 con list  uuid $CONNECTION_UUID | grep ^ipv4.dns-search | cut -f2- -d: | cut -f1 -d,)
	    interface="$1"
	fi
	;;

    vpn-down|down)
	UUID="$(nmcli -t --fields UUID con status)"
	NRCONS="$(echo "$UUID" | wc -l)"
	if [ "$NRCONS" = "1" ]; then
	    pac="$(nmcli -t --fields ip con status uuid $UUID | egrep '^DHCP4.OPTION\[[0-9]+\]:wpad = ' | cut -f3- -d\ )"
	    wpad_domain="$(nmcli -t --fields ip con status uuid $UUID | egrep '^IP4.DOMAIN\[1\]:' | cut -f2- -d:)"
	    interface="$(nmcli -t --fields general con status uuid $UUID | egrep '^GENERAL.DEVICES:' | cut -f2- -d:)"
	fi
	;;
esac

if [ "$pac" = "" ] && [ "$wpad_domain" != "" ]; then
    if curl -f -I http://wpad.${wpad_domain}/wpad.dat; then
	pac="http://wpad.${wpad_domain}/wpad.dat"
    fi
fi

# Actually turn this into a DBus call to prod it into PacRunner...
logger "interface:$interface pac:$pac"

