#!/bin/sh

# Kill the old and start the new amd.
# This is done here to keep amd alive across the update, in case the archives
# are on an automounted directory!
pid=""
tmpfile=""
if [ -s /var/run/amd-upgrade.pid ]; then
	tmpfile=/var/run/amd-upgrade.pid
	pid=`cat $tmpfile`
fi
TMP="/t""mp" # Shut up lintian, we know what we're doing here...
if [ "$pid" = "" -a -s $TMP/amd-upgrade.pid -a ! -L $TMP/amd-upgrade.pid ]; then
	# This is for upgrading from amd_upl102-16 or below, which wrote to /tmp
	# instead to /var/run; but explicitly check for the file being a symlink
	# to avoid threats.
	tmpfile=$TMP/amd-upgrade.pid
	pid=`cat $tmpfile`
fi
if [ "$pid" = "" ]; then
	# This code is used when upgrading from older amd versions, which didn't
	# write {/tmp,/var/run}/amd-upgrade.pid yet
	# A simple "/etc/init.d/amd stop" or start-stop-daemon doesn't work,
	# because they both would look for a process running /usr/sbin/amd, but
	# this is the new binary, and the process is still executing the old
	# version and thus won't be found. We can't also use killall, because this
	# also looks at the executable. pidof seems to be ok, it just compares
	# the name. 
	# If no amd is running at all, the "|| true" is needed to avoid an error.
	pid=`pidof /usr/sbin/amd || true`
fi

if [ -n "$pid" ]; then
	echo "Stopping old amd (pid $pid)."
	kill -15 $pid
	# let it cleanly shut down...
	sleep 5
fi
if [ -n "$tmpfile" ]; then
	rm -f $tmpfile
fi

#DEBHELPER#

exit 0
