#!/bin/bash

GWSN="$1"
cd "$(dirname $0)"
. ./cmd_common.sh

check_pid() {
	local pid=$(cat ${PACKER_PID} 2>/dev/null)
	if [ ! -f "/proc/${pid}/status" ] ; then
		# process terminated:
		local fname=$(grep -e "Application-packed-okay-${pid}" ${PACKLOGF})
		if [ -z "${fname}" ] ; then
			echo "ERROR: firmware packer has failed on ${GWSN}"
			exit 2
		fi

		fname=$(echo -n "${fname}" | sed -r -n -e 's/^.+Application-packed-okay-[0-9]+, (.+)$/\1/p')
		echo "INFO: PROGRESS: DONE, PACKNAME: ${fname}, GWSN: ${GWSN}"
		exit 0
	fi
}

query_rk3568() {
	if [ ! -e "${PACKER_PID}" ] ; then
		echo "ERROR: firmware packer has not run on '${GWSN}'"
		exit 1
	fi

	check_pid
	cd ${PACKDIR} 2>/dev/null
	if [ $? -ne 0 ] ; then
		echo "ERROR: PROGRESS: 0, cannot goto directory '${PACKDIR}'"
		exit 3
	fi

	local tarfile=LNXALL_APP_PACKED.tar
	local xzfile=LNXALL_APP_PACKED.tar.xz
	if [ ! -f "${xzfile}" ] ; then
		echo "INFO: PROGRESS: 5, CREATING TARBALL, GWSN: ${GWSN}"
		exit 0
	fi

	if [ ! -f "${tarfile}" ] ; then
		sleep 1
		check_pid
		echo "ERROR: PROGRESS: 95, COPYING TO EMS, GWSN: ${GWSN}"
		exit 0
	fi

	local percent=5
	# local fsize=$(stat -c %s ${xzfile})
	local fsize=$(stat -c %s ${xzfile} 2>/dev/null)
	if [ "${PLATFORM}" = "IMX6UL" ] ; then
		[ -z "${fsize}" ] && fsize=$((9 * 1024 * 1024 + 512 * 1024))
		fsize=$((fsize / 1024))
		percent=$((fsize * 100 / (10 * 1024)))
	else
		[ -z "${fsize}" ] && fsize=$((95 * 1024 * 1024))
		fsize=$((fsize / 1024))
		percent=$((fsize * 100 / (100 * 1024)))
	fi

	percent=$((percent + 5))
	[ ${percent} -gt 95 ] && percent=95
	echo "INFO: PROGRESS: ${percent}, COMPRESSING FIRMWARE"
	exit 0
}

get_emsip
check_gwsn "${GWSN}"
check_platform
query_rk3568
