#! /bin/sh

set -e

case "$1" in
	upgrade|install-upgrade)
		;;
	abort-upgrade)
		exit 0
		;;
esac
#
# Add the "proxy" user/group to /etc/passwd if needed.
#

if ! grep -q "^proxy:" /etc/passwd
then
	#
	#	Let's hope that this works; if /var/spool/squid3 is
	#	already present this fails :(
	#
	adduser --system --home /var/spool/squid3 --group proxy
	#
	# Change the shell so that cron jobs will work.
	# (They run as root now, but you can never know).
	#
	chsh -s /bin/sh proxy
fi

disable_profile() {
    APP_CONFFILE="/etc/apparmor.d/usr.sbin.squid3"
    APP_DISABLE="/etc/apparmor.d/disable/usr.sbin.squid3"
    # Create a symlink to the yet-to-be-unpacked profile
    if [ ! -e "$APP_CONFFILE" ]; then
        mkdir -p `dirname $APP_DISABLE` 2>/dev/null || true
        ln -sf $APP_CONFFILE $APP_DISABLE
    fi
}

if [ "$1" = "install" ]; then
    # Disable AppArmor profile on install
    disable_profile
elif [ "$1" = "upgrade" ] && dpkg --compare-versions "$2" lt "3.1.19-1ubuntu4" ; then
    # Disable AppArmor on upgrade from earlier than when we first shipped
    # the profile if the user does not already have a profile defined
    disable_profile
fi


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

#DEBHELPER#

# Because of this bug:
# https://bugs.launchpad.net/bugs/573853 
# Upstart may have lost track of squid. Correct that by using the
# pid file to stop it and then start the job back up
if [ "$1" = "upgrade" ] \
  && [ -f "/var/run/squid.pid" ] \
  && [ -f "/etc/init/squid3.conf" ]
then
	SQUID_PID=`cat /var/run/squid3.pid`
	# is this still running, and actually squid
	if [ -d "/proc/${SQUID_PID}" ] \
	 && [ "`stat -L -c %D%i /proc/${SQUID_PID}/exe`" = "`stat -L -c %D%i /usr/sbin/squid`" ]
	then
		UPSTART_SQUID_PID=`initctl status squid3 | awk -F'process ' '/start\/running, process / { print $2 }'`
		PIDFILE_PPID=`awk '{print $4}' /proc/$SQUID_PID/stat`
		# If the user has disabled expect fork the pids will be the same
		if [ "$UPSTART_SQUID_PID" != "$SQUID_PID" -a "$PIDFILE_PPID" != "$UPSTART_SQUID_PID" ]
		then
			# stop the job
			if invoke-rc.d squid3 stop
			then
				# kill the pid file pid
				kill ${SQUID_PID}
				# start the job again
				invoke-rc.d squid3 start
			fi
		fi
	fi
fi

#DEBHELPER#

exit 0
