#! /bin/bash

set -e

lrrd_sums="
008826a6aa273926ad3d3f14648297fb:/etc/lrrd/templates/lrrd-domainview.tmpl
b9392bbbf0c92338d3958eb68ce650e4:/etc/lrrd/templates/lrrd-nodeview.tmpl
6ab11f132495f409fb83b67598a4d24b:/etc/lrrd/templates/lrrd-overview.tmpl
412a16307c1ce81fe14eb74c953d7e8a:/etc/lrrd/templates/lrrd-serviceview.tmpl
6d86361a699097294f7eb07d3301e489:/etc/lrrd/templates/logo.gif
697bb8b5fdfc8a2f9d38bbfd56cd989c:/etc/lrrd/templates/style.css
530070017a8147fb54c0cc3c9f259a80:/etc/lrrd/server.conf
"

migrate() {
	local from=$1; shift;
	local to=$1; shift;
	
	[ -r "$from" -a ! -e "$to" ] || return 0;

	for pair in $lrrd_sums; do
		local sum=${pair%:*}
		local file=${pair#*:}

		[ "$file" = "$from" ] || continue;
		
		if [ "$(md5sum $file | cut -f1 -d' ')" = "$sum" ]; then
			return 0;
		fi
	done

	[ -d ${to%/*} ] || mkdir -p ${to%/*}

	cp -dp $from $to

	for subst in $*; do
		perl -pi -e $subst $to
	done
}

convert_from_lrrd() {

	[ -e /etc/lrrd/server.conf ] || return 0;

	echo -n "Creating initial Munin configuration based on your LRRD installation.."

	migrate /etc/lrrd/server.conf /etc/munin/munin.conf \
		's,^(\s*dbdir\s*)/var/lib/lrrd$,$1/var/lib/munin,' \
		's,^(\s*htmldir\s*)/var/www/lrrd$,$1/var/www/munin,' \
		's,^(\s*logdir\s*)/var/log/lrrd$,$1/var/log/munin,' \
		's,^(\s*rundir\s*)/var/run/lrrd$,$1/var/run/munin,' \
		's,^(\s*tmpldir\s*)/etc/lrrd/templates$,$1/etc/munin/templates,'
	
	for f in /etc/lrrd/templates/*; do
		case "$f" in
			/etc/lrrd/templates/lrrd-domainview.tmpl)
				migrate $f /etc/munin/templates/munin-domainview.tmpl
				;;
			/etc/lrrd/templates/lrrd-nodeview.tmpl)
				migrate $f /etc/munin/templates/munin-nodeview.tmpl
				;;
			/etc/lrrd/templates/lrrd-overview.tmpl)
				migrate $f /etc/munin/templates/munin-overview.tmpl
				;;
			/etc/lrrd/templates/lrrd-serviceview.tmpl)
				migrate $f /etc/munin/templates/munin-serviceview.tmpl
				;;
			*)
				migrate $f /etc/munin/templates${f#/etc/lrrd/templates}
				;;
		esac
	done

	migrate /var/lib/lrrd/lrrd-update.stats /var/lib/munin/munin-update.stats
	migrate /var/lib/lrrd/lrrd-graph.stats /var/lib/munin/munin-graph.stats

	for f in /var/lib/lrrd/*/*.rrd; do
		migrate $f /var/lib/munin${f#/var/lib/lrrd}
	done

	echo $'done.\nYour old LRRD configuration and data is left untouched.'
}

if [ "$1" = "install" -a -z "$2" ]; then
	convert_from_lrrd
fi

#DEBHELPER#
