#!/bin/sh

BACKUPDIR="/var/db/rrd"
BACKUPFILE="/conf/rrd.tgz"
BACKUPOFF="<rrdbackup>-1</rrdbackup>"

if [ "$(grep -c "${BACKUPOFF}" /conf/config.xml)" != "0" ]; then
	rm -f ${BACKUPFILE}
elif [ "${1}" = "restore" ]; then
	if [ -f "${BACKUPFILE}" ]; then
		tar -C / -xzpf "${BACKUPFILE}"
		for XML in $(find "${BACKUPDIR}" -name "*.xml"); do
			/usr/local/bin/rrdtool restore -f "${XML}" "${XML%.xml}.rrd"
		done
	fi
else
	if [ -d "${BACKUPDIR}" ]; then
		for RRD in $(find "${BACKUPDIR}" -name "*.rrd"); do
			/usr/local/bin/rrdtool dump "${RRD}" "${RRD%.rrd}.xml"
		done
		tar -C / -czf "${BACKUPFILE}" ."${BACKUPDIR}"
	fi
fi

rm -f ${BACKUPDIR}/*.xml
