#!/bin/sh /etc/rc.common
 
EXTRA_COMMANDS="backup restore"
EXTRA_HELP="        backup  Backup vnstat database
        restore Restore vnstat database
"
 
START=50
STOP=60
 
vnstat_option() {
    sed -ne "s/^[[:space:]]*$1[[:space:]]*['\"]\([^'\"]*\)['\"].*/\1/p" /etc/vnstat.conf
}
 
BACKUP_FILE=/etc/vnstat_backup.tar.gz
LOGGER_TAG=vnstat_backup
VNSTAT_DIR="$(vnstat_option DatabaseDir)"
[ -n "$VNSTAT_DIR" ] || VNSTAT_DIR="/var/lib/vnstat"

_chk_omrquota() {
	config_get enabled $1 enabled
	[ "$enabled" = "1" ] && backup="true"
}

_backup_enabled() {
	backup="false"
	config_load omr-quota
	config_foreach _chk_omrquota interface
	[ "$(uci -q get openmptcprouter.settings.vnstat_backup)" = "1" ] && backup="true"
	[ "$backup" = "true" ]
}

backup_database() {
	if _backup_enabled; then
		if [ ! -d $VNSTAT_DIR ]; then
			logger -t $LOGGER_TAG -p err "cannot backup, data directory $VNSTAT_DIR does not exist (yet)"
		else
			logger -t $LOGGER_TAG -p info "backing up database"
			# A power cut while tar writes left a truncated archive in
			# place of the last good one
			/bin/tar -zcf $BACKUP_FILE.tmp -C $VNSTAT_DIR . && mv -f $BACKUP_FILE.tmp $BACKUP_FILE
			rm -f $BACKUP_FILE.tmp
		fi
	fi
}
 
restore_database() {
	if [ -f $BACKUP_FILE ]; then
		logger -t $LOGGER_TAG -p info 'restoring database'
		[ ! -d $VNSTAT_DIR ] && mkdir $VNSTAT_DIR
		/bin/tar -xzf $BACKUP_FILE -C $VNSTAT_DIR
	fi
}
 
# The package's postinst runs start too: restoring then put the archive,
# hours or days old, over the live database. Only at boot, while vnstatd
# (START=60) has not created it yet, and only when backups are on.
start() {
	[ -n "$(ls -A $VNSTAT_DIR 2>/dev/null)" ] && return 0
	_backup_enabled || return 0
	restore_database
}
 
stop() {
	backup_database
}
 
backup() {
	backup_database
}
 
restore() {
	restore_database
}
