#! /bin/sh

. /usr/share/debconf/confmodule

db_version 2.0

set -e

# exit if the config file is not present
if [ ! -e /etc/uptimed.conf ]; then
	exit 0
fi

if [ "$1" = "configure" ]; then
# Step 1: Assemble a sed(1) script that does the configuration changes we
#         want
	SEDSCRIPT=`mktemp /tmp/debconfXXXXXX`
	db_get 'uptimed/interval'
	echo >$SEDSCRIPT "s/^UPDATE_INTERVAL=.*/UPDATE_INTERVAL=$RET/"
	db_get 'uptimed/maxrecords'
	echo >>$SEDSCRIPT "s/^LOG_MAXIMUM_ENTRIES=.*/LOG_MAXIMUM_ENTRIES=$RET/"
	db_get 'uptimed/mail/do_mail'
	if [ "$RET" = "Never" ]; then
		echo >>$SEDSCRIPT "s/^SEND_EMAIL=.*/SEND_EMAIL=0/"
	elif [ "$RET" = "Record" ]; then
		echo >>$SEDSCRIPT "s/^SEND_EMAIL=.*/SEND_EMAIL=3/"
	elif [ "$RET" = "Milestone" ]; then
		echo >>$SEDSCRIPT "s/^SEND_EMAIL=.*/SEND_EMAIL=2/"
	else
		echo >>$SEDSCRIPT "s/^SEND_EMAIL=.*/SEND_EMAIL=1/"
	fi
	if [ "$RET" != "Never" ]; then
		db_get 'uptimed/mail/address'
		echo >>$SEDSCRIPT "s/^EMAIL=.*/EMAIL=$RET/"
	fi
	# 0.1.6-4 commented these out. Leave until the yet unnamed distro
	# after sid
	echo >>$SEDSCRIPT "s/^#disabled#MILESTONE=/MILESTONE=/"

	db_stop

# Step 2: Process the config file
	TEMPFILE=`mktemp /tmp/debconfXXXXXX`
	sed -f $SEDSCRIPT </etc/uptimed.conf >$TEMPFILE
	rm $SEDSCRIPT

# Step 3: See if anything has changed. If so, install the new configuration
#         and restart uptimed
        if diff /etc/uptimed.conf $TEMPFILE >/dev/null; then
                rm $TEMPFILE
        else
                mv /etc/uptimed.conf \
                        /etc/uptimed.conf.dpkg-old
                mv $TEMPFILE /etc/uptimed.conf
        fi
	chmod 644 /etc/uptimed.conf
	chown daemon:daemon /var/spool/uptimed

# Step 4: Fixup uptimed db files wrt. to #654830
	invoke-rc.d uptimed stop
        if dpkg --compare-versions "$2" '<<' '1:0.4.6-1~~'; then
            if [ -f /var/spool/uptimed/records ]; then
                /usr/libexec/uptimed/fixup-duplicate-uprecords
            fi
            if [ -f /var/spool/uptimed/records.old ]; then
                /usr/libexec/uptimed/fixup-duplicate-uprecords -b
            fi
        fi
	invoke-rc.d uptimed start
fi

#DEBHELPER#
