#!/bin/sh

IMGPATH="/userdata/upgrade/fireware.img"
STATUSDIR="/oem/.onvif_upgrade"
STATUSPATH="${STATUSDIR}/status"
[ ! -d "${STATUSDIR}" ] && mkdir -p ${STATUSDIR}

get_mac() {
    real_model="`/etc/scripts/getmodel.sh`"
    if [ "foo${real_model}" = "fooX10" -o "foo${real_model}" = "fooX10_V2" ];then
        interface="br0"
    else
        interface="eth0"
    fi
    echo "`ifconfig ${interface} | grep HWaddr | awk '{print $5}' | tr -d ':' | tr -d ' '`"
}

action="$1"

[ -z "${action}" ] && exit 1

case "${action}" in
	upgrade)
		echo -n "UpgradePre" > ${STATUSPATH}
		sync
		[ -z "$2" -o -z "$3" ] && exit 1
		/etc/scripts/upgrade.sh pre
		fireware="$2"
		reset_default="$3"
		echo -n "Downloading" > ${STATUSPATH}
		#"Zycoo-X10 v_s1.2.5 68692E290C5D"
		model="`sysconf ${SYSTEMCONF} get system oem_model`"
		[ -z "${model}" ] && model="`sysconf ${SYSTEMCONF} get system model`"
		softwareVersion="`sysconf ${SYSTEMCONF} get system firmware`"
		mac="`get_mac`"
		user_agent="Zycoo-${model} ${softwareVersion} ${mac}"
		retcode="`/usr/bin/curl -o ${IMGPATH} -k --user-agent "${user_agent}" --connect-timeout 10 -w %{http_code} ${fireware}`"
		if [ "foo${retcode}" != "foo200" ];then
			echo -n "downloadError" > ${STATUSPATH}
			rm -rf ${IMGPATH}
			sync
			exit 1
		fi
		echo -n "Verifying" > ${STATUSPATH}
		sync

		model="`/etc/scripts/getmodel.sh`"
		[ -z ${model} ] && exit 1
		/usr/bin/rk_parser ${IMGPATH} ${model}
		recode_check="$?"
		if [ "foo${recode_check}" != "foo0" ];then
			echo -n "VerifyFailed" > ${STATUSPATH}
			rm -rf ${IMGPATH}
			sync
			exit 1
		fi
		sync

		/etc/scripts/shell_action.sh showReboot
		updatetime="`sysconf /etc/speaker.conf get upgrade date`"

		if [ ! -f /userdata/updatetime.txt ];then
			touch /userdata/updatetime.txt
			cat << END > /userdata/updatetime.txt
[upgrade]
date=2019-12-02
END
        	fi

		sysconf /userdata/updatetime.txt set upgrade date ${updatetime}
		echo -n "Upgrading" > ${STATUSPATH}
		touch ${STATUSDIR}/upgraded
		touch ${STATUSDIR}/mqtt_upgraded
		sync

		sleep 4

        if [ "foo${reset_default}" = "foono" ];then
            rm -rf /oem/.upgrade
            #updateEngine --image_url=${para} --misc=update --savepath=${para}  --reboot
            tar -zxvf ${para} -C /
            recode="$?"
            if [ "${recode}" = 255 ];then
                touch /oem/.upgrade
                rm -rf ${para}
                sync
                exit 1
            fi
        else
            rm -rf /oem/.userdata
            # updateEngine --image_url=${para} --misc=update --savepath=${para}  --reboot
            tar -zxvf ${para} -C /
            recode="$?"
            if [ "${recode}" = 255 ];then
                touch /oem/.userdata
                rm -rf ${para}
                sync
                exit 1
            fi
        fi
		sync
	;;

	getStatus)
		cat ${STATUSPATH}
		exit 0
	;;
esac

exit 0