#!/bin/sh
#
# This is the postinst script for the Debian GNU/Linux apmd package
#
# Written by Dirk Eddelbuettel <edd@debian.org>
# Debconf changes added by Chris Hanson <cph@debian.org>

set -e 

# Do debconf processing.
if [ "${1}" = "configure" ]; then
    CONFFILE=/etc/apm/apmd_proxy.conf
    TEMPLATE=/usr/share/apmd/apmd_proxy.conf
    SEDFILE=${CONFFILE}.sed.$$
    TMPFILE=${CONFFILE}.tmp.$$

    trap "rm -f ${SEDFILE} ${TMPFILE}" EXIT SIGINT SIGQUIT SIGTERM

    . /usr/share/debconf/confmodule || exit 0

    # Determine whether the file is under debconf control.
    # Otherwise it has been hand-modified by the user and we
    # shouldn't change it.
    db_get apmd/etc-apmd-md5 || true
    MD5="${RET}"
    if [ -e "${CONFFILE}" ]; then
	MD5A="$(md5sum < "${CONFFILE}")"
    else
	MD5A="not-present"
    fi
    if [ "${MD5}" = "${MD5A}" ]; then
	# Convert the debconf bindings to a sed script that will
	# insert the bindings into the configuration file.
	rm -f "${SEDFILE}" || true
	xfer_binding ()
	{
	    db_get "${1}" || true
	    echo "s%^${2}=\(.*\)\$%${2}=${RET}%;" >> "${SEDFILE}"
	}
	xfer_binding apmd/suspend-on-ac "SUSPEND_ON_AC"
	xfer_binding apmd/hdparm-drive "HDPARM_DRIVE"
	xfer_binding apmd/hdparm-spindown "HDPARM_SPINDOWN"

	# Generate a new copy of the configuration file.
	cat "${TEMPLATE}" | sed -f "${SEDFILE}" > "${TMPFILE}"
	rm -f "${SEDFILE}" || true

	# Compare the new file to the old, and overwrite old if
	# they are different.
	NEWMD5="$(md5sum < ${TMPFILE})"
	if [ "${MD5}" = "${NEWMD5}" ]; then
	    rm -f "${TMPFILE}" || true
	else
	    mv -f "${TMPFILE}" "${CONFFILE}"
	    db_set apmd/etc-apmd-md5 "${NEWMD5}" || true
	fi
    fi
    db_stop
fi

#DEBHELPER#

if [ ! -e /proc/apm ]
then
    echo    ""
    echo -n "The apmd package requires kernel support which is missing "
    echo    "from the kernel"
    echo -n "that is currently running. You need to recompile your kernel "
    echo    "to use apmd, or give lilo the 'apm=on' option when booting."
    echo    ""
fi

case "$1" in
    configure)
	update-rc.d apmd defaults >/dev/null
	/etc/init.d/apmd start
	;;
    abort-upgrade|abort-remove|abort-deconfigure)
	exit 0
	;;
    *)
	echo "postinst called with unknown argument \`$1'" >&2
	exit 0
	;;
esac
