#!/bin/sh
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/bin/X11:/usr/local/bin:/opt/yhcharger/bin:/opt/yhcharger/bin/lib
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/yhcharger/bin/lib

SecurityLogFile=/opt/yhcharger/data/securityLog
TimeStamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

SRC_FILE="IocHomeRelease-am3354-lib-evse-lcd8-20260730-122841.ezp"
if [ -f IocRelease.sig ]; then
	openssl dgst -verify ioc_charger_pub.pem -sha256 -signature IocRelease.sig $SRC_FILE
else
	openssl dgst -verify ioc_charger_pub.pem -sha256 -signature IocHomeRelease.sig $SRC_FILE
fi
if [ "$?" != "0" ]; then
	echo "Verify Failed"
	echo "$TimeStamp,InvalidFirmwareSignature,Upg dgst" >> $SecurityLogFile
	exit 1
else
	INPUT_TYPE=${SRC_FILE##*.}
	if [ "$INPUT_TYPE" = "ezp" ]; then
		echo "Decrypt EZP"
		./DecryptUpg.exe $SRC_FILE tmpdec.tzp
		if [ ! -f tmpdec.tzp ]; then
			echo "Decrypt EZP Failed"
			echo "$TimeStamp,InvalidFirmwareSignature,Upg Decrypt EZP" >> $SecurityLogFile
			exit 2
		fi
		rm -f $SRC_FILE 	# 删除文件, 释放内存空间

		echo "Unzip TZP"
		unzip -q -o tmpdec.tzp
		SRC_FILE=${SRC_FILE%.*}.tar
		if [ ! -f $SRC_FILE ]; then
			echo "Unzip TZP Failed"
			echo "$TimeStamp,InvalidFirmwareSignature,Upg Unzip TZP" >> $SecurityLogFile
			exit 3
		fi
		rm -f tmpdec.tzp 	# 删除文件, 释放内存空间
	fi
	mkdir -p upgtar
	cd upgtar
	tar -xvf ../$SRC_FILE >>/dev/null
	rtn=$?
	if [ $rtn -ne 0 ]; then
		echo "UnTar Failed"
		quit $rtn
		exit 	
	fi	
	rm -f ../$SRC_FILE # 删除文件, 释放内存空间
	./IocUpgrade.sh
	rtn=$?
	echo "Sync File"
	sync
	exit $rtn
fi
