#!/bin/sh

DIR=vnstat
WORK_DB_DIR=/tmp/$DIR
ARCH_DB_DIR=/gsw/$DIR
START_FLG=/tmp/vnstat.flg
DAEMON_SCRIPT=/gsw/etc/rc.d/init.d/vnstat

do_start() {
	if [ ! -e "$START_FLG" ]; then
		if [ ! -d "$WORK_DB_DIR" ]; then
			if [ -d "$ARCH_DB_DIR" ]; then
				cp -fr $ARCH_DB_DIR $(dirname $WORK_DB_DIR)
			else
				mkdir $WORK_DB_DIR
				chmod 0777 $WORK_DB_DIR
			fi
		fi
		touch $START_FLG
	fi
}

do_stop() {
	do_save
	rm -f $START_FLG
}

do_connect() {
	if [ -e "$START_FLG" ]; then
		if [ ! -e "$WORK_DB_DIR/$1" ]; then
			vnstat -u -i $1
			$DAEMON_SCRIPT restart
		fi
	fi
}

do_save() {
	if [ -e "$START_FLG" ]; then
		if [ -d "$WORK_DB_DIR" ]; then
			cp -fr $WORK_DB_DIR $(dirname $ARCH_DB_DIR)
		fi
	fi
}

do_check() {
	if [ -e "$START_FLG" ]; then
		echo "[on]"
	else
		echo "[off]"
	fi
}

case "$1" in
	start)
		do_start
	;;
	stop)
		do_stop
	;;
	connect)
		do_connect $2
	;;
	db_save)
		do_save
	;;
	check)
		do_check
	;;
	*)
		echo "Usage: $0 start|stop|connect <iface>|db_save|check" >&2
		exit 3
	;;
esac

exit 0
