#!/bin/sh

# Bring up/down http proxy

. /bin/network-functions

SETSID=/usr/bin/setsid
PIDFILE=/var/run/tinyproxy.pid
SERVICE=httpproxyd
PROCESS_NAME=tinyproxy

KILLALL=/usr/bin/killall
make_filter ()
{
	# Create filter
	# Add all IPs of interfaces and IPs of IP Phones
	if [ ! -d /etc/fiad-conf/tinyproxy ]; then
	    mkdir -p /etc/fiad-conf/tinyproxy
	fi

	ifconfig | awk -F "[: ]+" '/inet addr:/ { if ($4 != "127.0.0.1") print $4 }' > /etc/fiad-conf/tinyproxy/whitelist
	cat /etc/telephony/ipphones_reg_status | awk -F "[= ]+" '/bnd_realaddr=/ { print $2 }' >> /etc/fiad-conf/tinyproxy/whitelist

	# remove duplicates
	sort -u -o /etc/fiad-conf/tinyproxy/whitelist /etc/fiad-conf/tinyproxy/whitelist

}

do_start ()
{
	if ! ServiceCheckRunning1 ; then
		return $?
	fi
	
	#make_filter
	
	$SETSID /bin/$PROCESS_NAME -c /etc/tinyproxy/tinyproxy.conf >/dev/null 2>/dev/null
	
	ServiceCheckRunning2
	
	return $?
}

do_stop ()
{
	ServiceStop

	return $?
}

do_status ()
{
	ServiceStatus
	return $?
}

do_reload ()
{
	#make_filter
	pid=$(cat $PIDFILE)
	kill -SIGHUP $pid
}

case "$1" in
	start)
		do_start
		;;
	stop)
		do_stop
		;;
	reload)
		do_reload
		;;
	status)
		do_status
		;;
	restart)
		do_stop
		do_start
		;;
	*)
		echo "Usage: $0 {start|stop|status|restart|reload}"
		exit 1
esac

exit $?
