#!/bin/sh
#
# Usage: modsave [flash|all]

save() {
	local TMPFILE=/tmp/.save.tmp
	local FLASHFILE=/var/flash/freetz
	local rc=0
	local MSG

	local MOD_LIMIT=$((32*1024))

	# not really a lock
	if [ -e "$TMPFILE" ]; then
		echo "$TMPFILE exists! Concurrent update?" 1>&2
		exit 1
	fi

	tar -cf $TMPFILE flash -C /tmp/

	# compressed config size must be less than 32 KB (~32330Bytes)
	size=$(gzip -c $TMPFILE | wc -c)
	if [ "$size" -gt "$MOD_LIMIT" ]; then
		rm -f $TMPFILE
		echo "ERROR: $FLASHFILE too big: compressed size: $size, limit: $MOD_LIMIT" 1>&2
		exit 1
	fi

	echo -n "Checking Freetz configuration ... "
	if cmp -s $FLASHFILE $TMPFILE; then
		echo "unchanged."
	else
		echo "changed."
		echo -n "Writing $size bytes to $FLASHFILE ... "
		MSG=$(cat $TMPFILE 2>&1 > $FLASHFILE)
		rc=$?
		if [ $rc -ne 0 ]; then
			echo "write failed: $MSG"
			rc=1
		elif ! cmp -s $FLASHFILE $TMPFILE; then
			echo "verify failed."
			rc=1
		else
			echo "done."
		fi
	fi
	if [ $rc -ne 0 ]; then
		mv -f $TMPFILE $TMPFILE.sav
	fi
	rm -f $TMPFILE
	exit $rc
}

case $1 in
	""|all)
		echo -n 'Saving users, groups and passwords ... '
		/usr/bin/modusers save
		echo 'done.'

		echo -n 'Saving config ... '
		/usr/bin/modconf save mod
		for pkg in $(cat /mod/etc/static.pkg 2>/dev/null); do
			if [ -r "/mod/etc/default.$pkg/$pkg.cfg" ]; then
				/usr/bin/modconf save "$pkg"
			fi
		done
		echo 'done.'

		save
		;;
	flash)
		save
		;;
	*)
		echo "Usage: $0 [flash|all]" 1>&2
		exit 1
		;;
esac

exit 0
