#! /bin/sh

set -e

prevver="$2"

add_munin_system_user() {
	if ! getent passwd munin >/dev/null; then
		adduser --group --system --no-create-home --home /var/lib/munin munin
	fi
	# workaround bug (#531021) in xen-tools
	if ! getent group munin >/dev/null; then
		addgroup --system munin
		adduser munin munin
	fi
}

initperms() {
	mkdir -p /var/lib/munin/plugin-state 

	chown munin:adm /var/log/munin
	chmod 755 /var/log/munin
	
	chown munin:munin /var/lib/munin
	chmod 755 /var/lib/munin

	chown munin:munin /var/lib/munin/plugin-state
	chmod 755 /var/lib/munin/plugin-state

	chown root:munin /etc/munin/plugin-conf.d
	chmod 750 /etc/munin/plugin-conf.d
}

fixoverrides() {

        overrides="
/etc/munin/plugin-conf.d
/var/lib/munin
/var/lib/munin/plugin-state
/var/log/munin
"

        for override in $overrides; do
                if dpkg-statoverride --list $override >/dev/null; then
                        dpkg-statoverride --remove $override
                fi
        done
}

init_plugins() {
	TMPFILE=`mktemp /tmp/munin-node.configure.XXXXXXXXXX`
	TMPFILE_STDERR=`mktemp /tmp/munin-node.configure.err.XXXXXXXXXX`
	MUNIN_NODE_CONF_LOG="/var/log/munin/munin-node-configure.log"
	if [ "$prevver" ]; then
		MUNIN_NODE_CMD="munin-node-configure --shell --newer "${prevver%-*}""    
		echo -n "Initializing new plugins.."
	else
		MUNIN_NODE_CMD="munin-node-configure --shell"
		echo -n "Initializing plugins.."
    fi

	# munin-node-conf returns 1 if case of partial plugin autoconf
	# errors. We need to ignore these errors as even one plugin
	# can fail the entire process. See Debian bug #539886 for details.
	$MUNIN_NODE_CMD 2>$TMPFILE_STDERR >$TMPFILE || true
	if [ -f $TMPFILE ]; then
		DATE=`date '+%b %d %T'`
		echo "$DATE - Starting $MUNIN_NODE_CMD" >> $MUNIN_NODE_CONF_LOG
		cat $TMPFILE >> $MUNIN_NODE_CONF_LOG
        if [ -s $TMPFILE_STDERR ]; then
			echo "The following errors were reported by $MUNIN_NODE_CMD" \
			>> $MUNIN_NODE_CONF_LOG 
			cat $TMPFILE_STDERR >> $MUNIN_NODE_CONF_LOG
        fi
		sh < $TMPFILE
	else 
		echo "failed."
	fi
	echo "done."
	rm -f $TMPFILE $TMPFILE_STDERR
	echo -n "Restarting munin-node.."
	invoke-rc.d munin-node restart
}

case "$1" in
	configure)
		add_munin_system_user
		# this can go away after wheezy
		if dpkg --compare-versions "$2" le "2.0~rc5-1"; then
			fixoverrides
		fi
		# do this on upgrades (from old versions) and on new installs
		if dpkg --compare-versions "$2" le "2.0~rc5-2" || [ "$2" = 0 ] ; then
			initperms
		fi
		init_plugins
		;;
        triggered)
		if [ "$2" = "perl-major-upgrade" ]; then
			invoke-rc.d munin-node restart
		fi
		;;
	abort-upgrade|abort-deconfigure|abort-remove)
		:
		;;
	*)
		echo "Called with unknown argument $1, bailing out."
		exit 1
		;;
esac

#DEBHELPER#
