#!/usr/bin/sh

create_cksum_file() {
	srcfile=$1
	destfile=$2
	cksumfile=$3

	echo "# DO NOT EDIT OR REMOVE THIS FILE - It is used to determine whether to" > $cksumfile
	echo "# overwrite $destfile on package update or to remove" >> $cksumfile
	echo "# it on package deletion." >> $cksumfile
	/usr/bin/cat $srcfile | /usr/bin/cksum >> $cksumfile
	/usr/bin/chmod 400 $cksumfile
}

compare_cksum() {
	destfile=$1
	cksumfile=$2

	installed_cksum=`/usr/bin/tail -1 $cksumfile | /usr/bin/awk '{print $1}'`
	current_cksum=`/usr/bin/cksum $destfile | /usr/bin/awk '{print $1}'`
	test $installed_cksum = $current_cksum
}

while read src dest ; do
	destpath=`echo $dest | /usr/bin/sed -e 's/\/[^/]*$//'`
	destbase=`/usr/bin/basename $dest`
	cksumfile="${destpath}/.${destbase}.cksum"
	if [ -f $dest ] ; then
		if [ -f $cksumfile ] ; then
			compare_cksum $dest $cksumfile
			if [ $? -eq 0 ] ; then
				/usr/bin/cp $src $dest
				/usr/bin/chmod 600 $dest
				/usr/bin/chown nagios:nagios $dest
			else
				echo "Existing $dest has been found --"
				echo "    installing $destbase as $dest.pkgnew"
				/usr/bin/cp $src $dest.pkgnew
				/usr/bin/chmod 600 $dest.pkgnew
				/usr/bin/chown nagios:nagios $dest.pkgnew
			fi
		else
			echo "Existing $dest has been found --"
			echo "    installing $destbase as $dest.pkgnew"
			/usr/bin/cp $src $dest.pkgnew
			/usr/bin/chmod 600 $dest.pkgnew
			/usr/bin/chown nagios:nagios $dest.pkgnew
		fi
	else
		create_cksum_file $src $dest $cksumfile
		/usr/bin/cp $src $dest
		/usr/bin/chmod 600 $dest
		/usr/bin/chown nagios:nagios $dest
	fi
done
if [ "$1" = "ENDOFCLASS" ] ; then
	exit 0
fi
