#!/bin/sh
# Copyright (C) 2006 OpenWrt.org 

#START=99

factory_mode_flag=`/bin/config get factory_mode`
if [ "x$factory_mode_flag" = "x1" ]; then
	exit 0
fi

rae_partion=$(part_dev rae)
panic_partion=$(part_dev crashinfo)
RAE_DIR=/tmp/router-analytics
RAE_DATA=$RAE_DIR/ra_data
CONFIG=/bin/config

if [ ! -e "/tmp/router-analytics" ];then
	mkdir -p /tmp/router-analytics
fi

if [ "x$(/bin/config get force_clean_ranvram_flag)" != "x1" ]; then
	/bin/config unset RA_stage
	/bin/config set force_clean_ranvram_flag=1
	/bin/config commit
fi
if [ "x$(/bin/config get RA_stage)" = "x" ];then
	/bin/config set RA_stage=prod
	/bin/config commit
fi

if [ "$(/bin/config get dgc_flash_type)" != "EMMC" -a "x$(ubinfo -a |grep vol_ntgrdata)" = "x" ];then
	ubinfo -a | grep vol_rae  || {
		# make a new volume on ubi0 by default. Any better idea to remove the hardcode "/dev/ubi0"?
		ubimkvol /dev/ubi0 -N vol_rae -s 2MiB
	}
fi

partition_init()
{
	[ ! -d $RAE_DIR ] && mkdir -p $RAE_DIR
	if [ "x$(ubinfo -a |grep vol_ntgrdata)" != "x" ]; then
		mkdir -p /tmp/ntgrdata/ra_data
		ln -s /tmp/ntgrdata/ra_data $RAE_DATA
	elif [ "x$(ubinfo -a |grep vol_ntgr)" != "x" ]; then
		mkdir -p /tmp/ntgr/ra_data
		ln -s /tmp/ntgr/ra_data $RAE_DATA
	else
		ra_data_partion=$(part_dev ra_data)
		[ ! -d $RAE_DATA ] && mkdir -p $RAE_DATA
		[ "x$ra_data_partion" != "x" ] && filetype=`blkid $ra_data_partion |grep -o 'TYPE=.*' |awk -F \" '{print $2}'`
		if [ "x$filetype" != "xext4" ];then
			mkfs.ext4 $ra_data_partion
		fi
		mount $ra_data_partion $RAE_DATA
	fi
	[ ! -d $RAE_DATA/installation ] && mkdir -p $RAE_DATA/installation
	#only run on base, MR2.x  use /tmp/orbi_type judge the orbi TYPE
}

start() {
	killall -9  aws-iot
	rm /var/run/aws_iot.pid
	if [ "$(/bin/config get ra_enable)" != "0" ]; then
		if [ ! -d /tmp/router-analytics/cloud_data ]; then
			mkdir -p /tmp/router-analytics/cloud_data/raw_data/backup
			mkdir -p /tmp/router-analytics/cloud_data/publish_data
		fi
		/usr/sbin/aws-iot
	else
		rm /tmp/router-analytics/cloud_data/ -rf
		/usr/sbin/aws-iot -t 86400 -o eventtype4
	fi
}

stop() 
{
	killall -9 aws-iot
	rm /var/run/aws_iot.pid
}

restart()
{
	stop
	start
}

erase()
{
	cd $RAE_DIR
	FILES="policy_version rae_version RAE_Policy.json /usr/sbin/aws-iot /usr/sbin/data_collector /usr/sbin/subscribe_publish_sample"
	rm $FILES -rf
	update
}

update()
{
	cd $RAE_DIR
	FILES="policy_version rae_version RAE_Policy.json /usr/sbin/aws-iot /usr/sbin/data_collector /usr/sbin/subscribe_publish_sample"
	tar -zcf rae.tar.gz $FILES
	if [ "x$(ubinfo -a |grep vol_ntgrdata)" != "x" ]; then
		cp -rf rae.tar.gz /tmp/ntgrdata/rae
		rm rae.tar.gz
	else
		dd if=/dev/zero bs=1024k count=1 |tr "\000" "\377" >1024kdata
		dd if=rae.tar.gz of=1024kdata conv=notrunc
		flash_erase $rae_partion 0 0
		cat 1024kdata > $rae_partion
		rm rae.tar.gz
		rm 1024kdata
	fi
	echo 1 >$RAE_DIR/status
}

check()
{
	echo 0 >$RAE_DIR/status
	if [ "x$(ubinfo -a |grep vol_ntgrdata)" != "x" ]; then
		cp -rf /tmp/ntgrdata/rae/rae.tar.gz /tmp
	else
		dd if=$rae_partion of=/tmp/rae.tar.gz
	fi
	tar -zxf /tmp/rae.tar.gz -C $RAE_DIR/
	tar_status=$?
	if [ -s $RAE_DIR/rae_version -a -s $RAE_DIR/policy_version -a -s $RAE_DIR/usr/sbin/aws-iot -a -s $RAE_DIR/usr/sbin/data_collector -a -s $RAE_DIR/usr/sbin/subscribe_publish_sample -a -s $RAE_DIR/RAE_Policy.json ];then
		mv $RAE_DIR/usr/sbin/* /usr/sbin/
		echo 1 >$RAE_DIR/status
		rm /tmp/rae.tar.gz -rf
		rm $RAE_DIR/usr -rf
	fi
}

get_last_panic_log()
{
	i=1
	while true 
	do
		dd if=$panic_partion of=$RAE_DIR/ra_crashlog bs=16384 skip=$i count=1
		num=`cat $RAE_DIR/ra_crashlog |head -1 |awk '{print $1}'`
		if [ "x$num" = "x" ];then
			i=$(($i-1))
			dd if=$panic_partion of=$RAE_DIR/ra_crashlog bs=16384 skip=$i count=1
			cat $RAE_DIR/ra_crashlog |tr '\n' ' ' > $RAE_DIR/crash_aws_log
			break;
		fi
		i=$(($i+1))
	done
	rm $RAE_DIR/ra_crashlog  $RAE_DIR/panic_log.txt
}

boot()
{
	[ "x$factory_mode_flag" = "x1" ] && exit

	#As NTGR Analytic_opt-in_opt-out spec:
	#There's a default value NVRAM RA_enable, WW, GR, PR SKU default is 0 not send RA, other SKU default is 1, will send RA
	#After user opt-in/opt-out analytic, after firmware upgrade/downgrade, the setting should be the same
	region=`artmtd -r region |grep REGION |awk -F " " '{printf $2}'`
	if [ "x$(/bin/config get RA_enable)" = "x" ];then
		if [ "$region" = "WW" -o "$region" = "GR" -o "$region" = "PR" ];then
			/bin/config set ra_enable=0
			/bin/config set RA_enable=0
		else
			/bin/config set ra_enable=1
			/bin/config set RA_enable=1
		fi
	fi

#	echo 1 > /tmp/debug_first_report_flag
#	if FW support router analytics installation , should create this file

	if [ "$(cat /tmp/orbi_type)" != "Satellite" ]; then
		partition_init
		echo 1 > /tmp/support_ra_installation
		/usr/sbin/ra_session_id
		/usr/sbin/install_agent
		/sbin/install_ping &
		hijack_status=`$CONFIG get dns_hijack`
	    install_state=`$CONFIG get installState`
		if [ "$hijack_status" = "1" ];then
			/usr/sbin/ra_installevent  sysReboot
		fi
		if [ "$install_state" = "13" ];then
			/usr/sbin/ra_installevent  fwupdatingsucess
		fi

		mkdir -p /tmp/router-analytics/cloud_data/raw_data/backup
		mkdir -p /tmp/router-analytics/cloud_data/publish_data
		d2 -c DalRaFolderPath[0].dalRaMemoryPath  /tmp/router-analytics/cloud_data/raw_data
		if [ "x`d2 -s DalRaFolderPath[0].dalRaNtpGetResult`" = "x" ];then
			d2 -c DalRaFolderPath[0].dalRaNtpGetResult No
		fi
	fi

	if [ "$(/bin/config get dgc_flash_type)" != "EMMC" ];then
		dd if=$panic_partion of=$RAE_DIR/panic_log.txt bs=131072 count=4
		dd if=$panic_partion of=$RAE_DIR/ra_crashlog bs=1 skip=131072 count=16384
		cat $RAE_DIR/ra_crashlog |tr '\n' ' ' > $RAE_DIR/crash_aws_log
		rm $RAE_DIR/ra_crashlog  $RAE_DIR/panic_log.txt
	else
		dd if=$panic_partion of=$RAE_DIR/panic_log.txt bs=16318 count=16
		get_last_panic_log
	fi

	
	[ "x$(/bin/config get lastRebootReason)" = "x" ] && /bin/config set lastRebootReason=0
	if [ -f /proc/reboot_reason ];then
		reboot_reason=`echo "obase=10;ibase=16;$(cat /proc/reboot_reason|awk -F 'x' '{print $2}')"|bc`
	else
		reboot_reason=0
	fi

	oom="0"
	oops="0"
	panic="0"
	watchdog="0"
	if [ "$(($(($reboot_reason >> 2))%2))" != "0" ];then
		#oom
		oom="1"
		/bin/config set lastRebootReason=1
	fi
	if [ "$(($(($reboot_reason >> 3))%2))" != "0" ];then
		#oops
		oops="1"
		/bin/config set lastRebootReason=1
	fi
	if [ "$(($(($reboot_reason >>  4))%2))" != "0" ];then
		#panic 
		panic="1"
		/bin/config set lastRebootReason=1
	fi
	if [ "$(($(($reboot_reason >> 5))%2))" != "0" ];then
		#watchdog reboot
		watchdog="1"
		/bin/config set lastRebootReason=1
	fi
	if [ "$(($(($reboot_reason >> 6))%2))" != "0" ];then
		#reset button reboot
		/bin/config set lastRebootReason=2
	fi
	if [ "$(($(($reboot_reason >> 7))%2))" != "0" ];then
		#reset button default
		/bin/config set lastRebootReason=3
	fi
	if [ "$(($(($reboot_reason))%2))" != "0" -o "$reboot_reason" == "0" ];then
		#unknown reboot
		[ "x$(/bin/config get lastRebootReason)" = "x" ] && /bin/config set lastRebootReason=0
	fi
	/bin/config set time_crash=`date +%s`
	if [ "x$(/bin/config get lastRebootReason)" = "x1" ];then
		[ -f $RAE_DIR/crash_aws_log ] || echo -n " "> $RAE_DIR/crash_aws_log
		if [ "$oom" = "1" ];then
			sed -i '1s/^/===Kernel oom===/' $RAE_DIR/crash_aws_log
		elif [ "$oops" = "1" ];then
			sed -i '1s/^/===Kernel oops===/' $RAE_DIR/crash_aws_log
		elif [ "$watchdog" = "1" ];then 
			sed -i '1s/^/===Kernel watchdog===/' $RAE_DIR/crash_aws_log
		else
			sed -i '1s/^/===Kernel panic===/' $RAE_DIR/crash_aws_log
		fi
	fi
	echo $(/bin/config get lastRebootReason) >/tmp/reboot_reason
	/bin/config set lastRebootReason=0

	check
	/bin/config set cpu_flag=1
	/bin/config set memory_flag=1
	/bin/config set eventtype=0
	/bin/config commit

	/sbin/ping-gateway &
	if [ "$(cat $RAE_DIR/status)" = "1" ]; then
		start
	else
		/usr/sbin/ra_check
		/usr/sbin/ra_daemon_monitor.sh &
	fi
}

cpu_test()
{
	for in in `seq $1`
	do 
		echo -ne "i=0;
		while true
		do 
			i=i+1;
		done" | /bin/sh &
		
	done
}

memory_test()
{
	if [ "$1" = 1 ]; then
		mkdir /tmp/memory
		mount -t tmpfs -o size=280M tmpfs /tmp/memory
		dd if=/dev/zero of=/tmp/memory/block
	else
		rm /tmp/memory/block
		umount /tmp/memory
		rmdir /tmp/memory
	fi
}

install_count_reset()
{
	echo 0 >$RAE_DATA/installation_count
}

install_count_add()
{
	[ ! -f $RAE_DATA/installation_count ] && echo 0 >$RAE_DATA/installation_count
	count=`cat $RAE_DATA/installation_count`
	if [ $count -lt 32 ];then
		count=$(($count+1))
		echo $count > $RAE_DATA/installation_count
	fi
	rm $RAE_DATA/duration
	rm $RAE_DATA/eventId
	rm $RAE_DATA/installation -rf
}

case "$1" in 
	"boot")
		boot
	;;
	"start")
		start
	;;
	"stop")
		stop
	;;
	"restart")
		restart
	;;
	"erase")
		erase
	;;
	"update")
		update
	;;
	"check")
		check
	;;
	"cpu")
		cpu_test  $2
	;;
	"memory")
		memory_test $2
	;;
	"reset")
		install_count_reset  ##only run when pot clean or ST SQA do test
	;;
	"default")      # run when default reset
		erase
		install_count_add
		rm $RAE_DATA/session_id
	;;
	*)
		echo "Unknow command" > /dev/console
		echo "Usage: $0 boot|start|stop|restart|erase|update|reset|default" > /dev/console
	;;
esac
