#!/bin/sh

# storeACL - read/write data to factory reset area

mode=$1
SAMSON=/bin/samson

restoreFromOldConfig()
{
	/bin/cp -f /mnt/flashfs/acldb.gz  /tmp/ > /dev/null 2>&1
	if [ "$?" != "0" ] ; then
		echo "No stored config. Create new from default"
		# no stored config.. create new from default
		/bin/cp -f /etc/acl_default.db /tmp/acldb
	else
		gzip -d -f /tmp/acldb.gz
	fi
	echo -n "Encryping acddb to samdb: "
	$SAMSON -ed -sf /tmp/acldb -ef /mnt/flashfs/samdb > /dev/null 2>&1
	RESULT=$?
	if [ "$RESULT" != "0" ] ; then
		# ups.. thats bad.. and now ?
		echo "failed"
		echo  "Result = $RESULT";
		exit 1
	fi
}

ReadData ()
{
	cd /tmp
	RESULT=0;
##	/bin/storefrdata -r -f /tmp/acldb.gz

	if [ ! -f /mnt/flashfs/samdb ] ; then
		echo "Encrypted file is missing. generating from /tmp/acldb"
		restoreFromOldConfig
		echo "OK"
	else
		if [ -f /mnt/flashfs/acldb.gz ] ; then
			echo "Found old config"
			rm -f /mnt/flashfs/samdb > /dev/null 2>&1
			restoreFromOldConfig
		fi

## check encrypted file validity
		echo -n "Checking samdb: "
		$SAMSON -chk -sf /mnt/flashfs/samdb > /dev/null 2>&1
		RESULT=$?
		if [ "$RESULT" != "0" ] ; then
			echo "failed"
			echo  "Result = $RESULT";
			
			/bin/cp -f /mnt/flashfs/acldb.gz  /tmp/ > /dev/null 2>&1
			if [ "$?" != "0" ] ; then
				echo -n "Create new from default: "
## file is invalid, restoring from default
				/bin/cp -f /etc/acl_default.db /tmp/acldb
				$SAMSON -ed -sf /tmp/acldb -ef /mnt/flashfs/samdb ## > /dev/null 2>&1
				RESULT=$?
				if [ "$RESULT" != "0" ] ; then
					# ups.. thats bad.. and now ?
					echo -n "failed. "
					echo  "Result = $RESULT";
					exit 1
				else
					echo "OK"
				fi
			else
				cd /tmp
				gzip -d -f /tmp/acldb.gz
				$SAMSON -ed -sf /tmp/acldb -ef /mnt/flashfs/samdb ## > /dev/null 2>&1
				RESULT=$?
				if [ "$RESULT" != "0" ] ; then
					# ups.. thats bad.. and now ?
					echo -n "failed. "
					echo  "Result = $RESULT";
					exit 1
				else
					echo "OK"
				fi
			fi
		else
			echo "OK"
		fi
	fi


## remove no encrypted acldb file
	if [ -f /tmp/acldb ] ; then
		/bin/rm -f /tmp/acldb
	fi
	
	/bin/rm -f /tmp/acldb.gz > /dev/null 2>&1
	/bin/rm -f /mnt/flashfs/acldb.gz > /dev/null 2>&1
}

case "$mode" in
	read)
		ReadData
		;;
	*)
		echo "unknown mode!"
		return 1
esac
