#!/bin/sh
# TP-LINK ganguoheng@tp-link.net
. /lib/functions.sh

cloud_unbind() {
	local bind_status=`uci get cloud.status.bind_status`
	if [ $bind_status == "1" ]; then
		local dev_id=`uci get tddp.deviceId.deviceId`
		local account_id=`uci get cloud.status.cloud_user_name`
		if [ ! $account_id ]; then
			return
		fi

		local request="{\"dev_id\":\"${dev_id}\",\"cloud_usr_name\":\"${account_id}\"}"
		ubus call cloud cloud_unbind ${request}

		uci set cloud.status.bind_status="0"
		uci set cloud.status.tplink_id_status="0"
		uci set cloud.status.reset_unbind_flag="1"
		uci commit
		cat /etc/config/cloud > /tmp/userconfig/etc/config/cloud
	fi
}
cloud_unbind

. /lib/functions.sh
. /lib/functions/userconfig.sh

rm -f /var/run/sleep_restorefactory.pid

# if restorfactory is on-going , just return 1 ?
if [ "$1" != "force" -a -f /var/run/restorefactory.pid ];then
    logger -p user.info -t "restorefactory" "restorfactory is on-going!"
    echo "restorefactory is on-going!" >/dev/console
    exit 1
fi;


# make a #.pid lock first.
rm -f /var/run/restorefactory.pid
echo $$ > /var/run/restorefactory.pid

logger -p user.info -t "restorefactory" "restoring to factory defaults ..."
echo " " >/dev/console
echo "##############################################" >/dev/console
echo "## restoring to factory defaults ...        ##" >/dev/console
echo "##############################################" >/dev/console
echo " " >/dev/console

# blink sys leds.
if [ -d /sys/class/leds/SYS_LED ];then
	/etc/init.d/led start
	echo 100 >/sys/class/leds/SYS_LED/delay_on
	echo 100 >/sys/class/leds/SYS_LED/delay_off
	uci set system.led_sys.delayon="100"
	uci set system.led_sys.delayoff="100"
	uci commit
	#sleep 2

	#echo 1000 >/sys/class/leds/SYS_LED/delay_on
	#echo 1000 >/sys/class/leds/SYS_LED/delay_off
fi;

###### custom restore commands begin ###### 
. /usr/sbin/logger_restore
cfg_reset_to_dftcfg 
RET=$?
if [ -f /lteconfig/SMS.db ];then
	rm -f /lteconfig/SMS.db
	sync
fi;

###### custom restore commands end ######
factorymode=`uci get tddp.factory_mode.flag`
echo "factorymode:$factorymode" >/dev/console
boot_done=`cat /tmp/boot_done`
if [ "$factorymode" == "1" -a "$boot_done" == "1" ]; then
	uci set tddp.factory_mode.flag=0
	uci commit tddp
	mtdtddp="$(find_mtd_part 'tddp')"
	echo "tddp in flash is $mtdtddp" >/dev/console
	cat /etc/config/tddp > $mtdtddp

	mtdtddp_b="$(find_mtd_part 'tddp.b')"
	if [ -n "$mtdtddp_b" ] ; then
		echo "tddp.b in flash is $mtdtddp_b" >/dev/console
		cat /etc/config/tddp > $mtdtddp_b
	fi
fi

# check if operation is success.
if [ "$RET" -ne "0" ];then
    logger -p user.info -t "restorefactory" "failed to erase rootfs_data partition, restorefactory failed!"
    echo "failed to erase rootfs_data partition, restorefactory failed!" >/dev/console
	exit 1
fi;

# umount the userconfig, avoid the kernel panic ...

umount /tmp/userconfig

sleep 3

exit 0






