#!/bin/sh
. /usr/syscfg/api_log.sh

SUCCESS="success"
ERR_FILE_EXIST="err_file_exist"
ERR_FILE_NONE="err_file_none"
ERR_FILE_FORMAT="err_file_format"
ERR_SPACE_USEDUP="err_space_usedup"
ERR_PARTITION_NONE="err_partition_none"

gEncryptedLeafArray="InternetGatewayDevice.ManagementServer.ConnectionRequestPassword InternetGatewayDevice.ManagementServer.Password InternetGatewayDevice.Services.VoiceService.1.VoiceProfile.1.Line.1.SIP.AuthPassword InternetGatewayDevice.Services.VoiceService.1.VoiceProfile.1.Line.2.SIP.AuthPassword WANPPPConnection.[0-9]*.Password"

action=$1
backup_config_path=$2


if [ -z "$backup_config_path" ]; then
	TGP_Log ${TGP_LOG_ERROR} "backup_config_path is empty!"
	exit 1
fi


ret=$SUCCESS

backup_judge()
{
	if [ -f "$backup_config_path" ]; then
		ret=$ERR_FILE_EXIST
	fi
}

restore_judge()
{
	if [ ! -f "$backup_config_path" ]; then
		ret=$ERR_FILE_NONE
	fi
}

backup()
{
	local tmp=''
	local path=''
	local value=''
	local encryptedValue=''

	dd if=/dev/mtd2 of=$backup_config_path
	for i in $gEncryptedLeafArray ; do
		tmp=`sed -n  /$i/p $backup_config_path`
		path=${tmp%%=*}
		value=${tmp#*=}
		if [ -z "$value" ];then
			continue
		fi
		encryptedValue=`echo $value | base64`
		sed -i s/$path=$value/$path=$encryptedValue/ $backup_config_path
	done
}

restore()
{
	local unencrypedValue=''


	for i in $gEncryptedLeafArray ; do
		tmp=`sed -n  /$i/p $backup_config_path`
		path=${tmp%%=*}
		value=${tmp#*=}
		if [ -z "$value" ];then
			continue
		fi
		unencrypedValue=`echo $value | base64 -d`
		sed -i s/$path=$value/$path=$unencrypedValue/ $backup_config_path
	done

	dd if=$backup_config_path of=/dev/mtdblock2

	rm -f $backup_config_path
}


case "$action" in
	"backup_judge")
		backup_judge
		echo -n $ret
		;;
	"restore_judge")
		restore_judge
		echo -n $ret
		;;
	"backup")
		#backup_judge
		if [ "${ret:0:3}" != "err" ]; then
			backup
		fi
		echo -n $ret
		;;
	"restore")
		restore_judge
		if [ "${ret:0:3}" != "err" ]; then
			restore
		fi
		echo -n $ret
		;;

	"clean")
		rm -f $backup_config_path
		exit 0
		;;

	"dump")
		restore_judge
		if [ "${ret:0:3}" != "err" ]; then
			cat $backup_config_path
			exit 0
		fi
		;;
esac

