#! /bin/sh

set -e

grepconf () {
	w=" 	" # space tab
	sq=/etc/squid3/squid.conf
	# sed is cool.
	res=`sed -ne '
		s/^'$1'['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
		t end;
		d;
		:end q' < $sq`
	[ -n "$res" ] || res=$2
	echo "$res"
}

grepconf2 () {
	w=" 	" # space tab
	sq=/etc/squid3/squid.conf
	# sed is cool.
	res=`sed -ne '
		s/^'$1'['"$w"']\+[^'"$w"']\+['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
		t end;
		d;
		:end q' < $sq`
	[ -n "$res" ] || res=$2
	echo "$res"
}

case "$1" in
	configure)
		#
		# Chown the directories.
		#
		log_dir=/var/log/squid3
		cache_dir=`grepconf2 cache_dir /var/spool/squid3`
		usr=`grepconf cache_effective_user proxy`
		grp=`grepconf cache_effective_group proxy`
		
		if [ "$(stat -c %U $cache_dir)" != "$usr" ] ||
		   [ "$(stat -c %G $cache_dir)" != "$grp" ] ; then
			chown $usr:$grp $cache_dir -R
		fi
		
		if [ "$(stat -c %U $log_dir)" != "$usr" ] ||
		   [ "$(stat -c %G $log_dir)" != "$grp" ] ; then
			if [ "$(dpkg-statoverride --list $log_dir)" = "" ] ; then
		  		chown -R $usr:$grp $log_dir
			fi
		fi
	 
		#
		# Create spool dirs if they don't exist.
		#
		if [ -d "$cache_dir" -a ! -d "$cache_dir/00" ]
		then
			echo "Creating Squid HTTP proxy 3.x spool directory structure"
			squid3 -z
		fi
		;;
	abort-upgrade|abort-remove|abort-deconfigure)
		;;
	*)
		#
		#	Unknown action - do nothing.
		#
		exit 0
		;;
esac

if [ -e "/etc/init/squid3.conf" ] ; then
	# Using stop/start because restart fails to reload the upstart job
    # file. See LP: #707479.
	invoke-rc.d squid3 stop || :
	invoke-rc.d squid3 start
fi

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
