#!/bin/sh

SERVER_IP=$1
FILE_NAME=$2
SKIP_TFTP=$3

echo -n "Configuration restore... "
if [ "$SKIP_TFTP" -ne "1" ]
then
	cd /tmp
	tftp -g -l cfg.tar.gz -r $FILE_NAME $SERVER_IP >/dev/null 2>&1
	[ -f /tmp/cfg.tar.gz ] || {
		echo "can not get config file from TFTP server, abort."
		return 1
	}
fi

cd /tmp
FILE_SIZE=
	eval `ls -l cfg.tar.gz | awk '{ print "FILE_SIZE=" $5 }'`
if [ "$FILE_SIZE" -eq "0" ]
then
	echo "empty file, abort."
	rm -f /tmp/cfg.tar.gz
	return 1
else
	#cd /etc/config
	#tar -zcf /tmp/cfg_backup.tar.gz *
	#rm -f *
	tar -zcf /tmp/cfg_backup.tar.gz /etc/persistence/config /www/langs /etc/persistence/data/ipsec.d/
	tar -tzf /tmp/cfg.tar.gz
	RETURN_VALUE=$?
	if [ "$RETURN_VALUE" = "0" ]
	then
		#rm -rf /etc/persistence/config
		OLD_CONFIG=$(tar -tzf /tmp/cfg.tar.gz | grep -c etc/config)
		if [ "$OLD_CONFIG" -ne "0" ]
		then
			tar -zxf /tmp/cfg.tar.gz etc/config -C /tmp
			mv /tmp/etc/config /etc/persistence/config
			rm -rf /tmp/etc/config
		else
			tar -zxf /tmp/cfg.tar.gz -C /
		fi
		
		# restore checksum
		mkdir -p /etc/persistence/checksum/config
		for file in $(ls /etc/config-default); do
			if [ -f /etc/config/$file ]; then
				md5sum /etc/config/$file | awk '{print $1}' > /etc/persistence/checksum/config/$file
			fi
		done

		echo "done"
		json set restore status=restoreSuccess
		return 0
	else
		echo "decompression failed"
		rm -f /tmp/cfg.tar.gz
		tar -zxf /tmp/cfg_backup.tar.gz -C /
		json set restore status=restoreFail
		return 1
	fi
fi
