systemd_units=(@_F_systemd_units@)

post_install()
{
	if ! grep -q '^munin:' /etc/group ; then
		groupadd -g 47 munin
	fi
	if ! grep -q '^munin:' /etc/passwd ; then
		useradd -u 47 -g 47 -s /bin/false -c "Munin User" -d /var/lib/munin munin
	fi

	# init plugins
	munin-node-configure --shell 2>/dev/null | sh

	local unit
	local op

	for i in ${systemd_units[@]}; do
		unit=$(echo $i | cut -f 1 -d '=')
		op=$(echo $i | cut -f 2 -d '=')
		if echo $op | grep -q 'e'; then
			systemctl enable $unit.service >/dev/null 2>&1
		fi
		if echo $op | grep -q 's'; then
			systemctl start $unit.service >/dev/null 2>&1
		fi
	done
}

post_upgrade()
{
	munin-node-configure --shell --newer "${0%-*}" | sh

	systemctl daemon-reload >/dev/null 2>&1
}

pre_remove()
{
	test -d /etc/munin/plugins/ && for plugin in $(find /etc/munin/plugins/ -type l); do
		if [ ! -e $(readlink $plugin) ]; then
			rm $plugin
		fi
	done

	local unit

	for i in ${systemd_units[@]}; do
		unit=$(echo $i | cut -f 1 -d '=')
		systemctl --no-reload disable $unit.service >/dev/null 2>&1
		systemctl stop $unit.service >/dev/null 2>&1
	done
}

post_remove()
{
	# if munin pkg installed then don't remove user&group
	if [ ! -f /usr/bin/munin-cron ]; then
		/usr/sbin/userdel -r munin >/dev/null 2>&1
		/usr/sbin/groupdel munin >/dev/null 2>&1
	fi
	
	# delete dangling symlinks
	rm -f /var/lib/munin/plugin-state/*.state
	rm -f /var/log/munin/munin-node.log*									

	systemctl daemon-reload >/dev/null 2>&1
}

op=$1
shift
$op $*
