#!/bin/bash

# Created by jiaqiang.ye@lnxall.com
# Pack on-device /opt/lnxall_app for release
# 2024/08/27

export PATH=/opt/lnxall_app/bin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin
cd "$(dirname $0)"
. ./cmd_common.sh

SEVAL=99
echo "$$" > ${PACKER_PID}

slog() {
	local LEVEL="$1"
	shift 1
	local msg="$@"
	[ -z "${msg}" ] && return 1

	logger -t PACKINST "${LEVEL} ${msg}"
	echo "$(date +%Y%m%d-%H%M%S): ${LEVEL}: ${msg}" >> ${PACKLOGF}
	return $?
}

exithandler() {
	rm -rf -v ${PACKDIR}/*.tar ${PACKDIR}/*.xz
	return 0
}

create_dir() {
	if [ ! -d "$1" ] ; then
		rm -rf "$1"
		mkdir -p "$1"
		return $?
	fi
	return 0
}

pack_init() {
	check_platform
	if [ $? -ne 0 ] ; then
		slog ERROR "cannot determine gateway device type."
		exit ${SEVAL}
	fi

	slog INFO "Found gateway device platform: ${PLATFORM}"
	get_emsip
	# create directories if not exists
	create_dir "${PACKDIR}"
	rm -rf ${PACKDIR}/*
	# 下面逻辑主要是为了解决导出包中/opt/lnxall_app/smu_files目录会包含屏控，安装导出elf的时候会使用这个目录下的zip屏控覆盖掉导出的屏控
	FILE_DIR=/opt/lnxall_app/smu_files
	[ -d "${FILE_DIR}" ] && rm -rf "${FILE_DIR}"

	return 0
}

pack_app() {
	cd /opt
	if [ $? -ne 0 ] ; then
		SEVAL=1
		slog ERROR "cannot goto directory /opt."
		exit ${SEVAL}
	fi

	local packdirs=lnxall_app
	if [ ! -d lnxall_app ] ; then
		SEVAL=2
		slog ERROR "lnxall_app directory not found."
		exit ${SEVAL}
	fi

	# copy lnxall-app-build-info.txt
	[ -f /etc/lnxall-app-build-info.txt ] && cp /etc/lnxall-app-build-info.txt ./lnxall_app/

	# check for emsd.service and emud.service
	rm -rf .lnxall_services/*
	mkdir -p .lnxall_services
	touch .lnxall_services/empty
	[ -e /etc/systemd/system/multi-user.target.wants/emsd.service ] && touch .lnxall_services/emsd.service
	[ -e /etc/systemd/system/multi-user.target.wants/emud.service ] && touch .lnxall_services/emud.service
	packdirs="${packdirs} .lnxall_services"

	# export system language settings
	rm -rf .lnxall_system/*
	mkdir -p .lnxall_system/default
	touch .lnxall_system/empty
	[ -f /etc/default/locale ] && cp -v -f /etc/default/locale .lnxall_system/default/locale
	packdirs="${packdirs} .lnxall_system"

	[ -e elect_resources ] && packdirs="${packdirs} elect_resources"
	slog INFO "Packing tarball -> ${packdirs}..."
	tar '--exclude=lnxall_app/app/database/*' \
		'--exclude=lnxall_app/app/temp/*' \
		'--exclude=elect_resources/resources/app/uploads/*' \
		'--exclude=elect_resources/resources/app/web/dist/exdata/*' \
		'--exclude=elect_resources/resources/app/node_modules' \
		-cf "${PACKDIR}/${PACKFILE}" ${packdirs}
	if [ $? -ne 0 ] ; then
		SEVAL=3
		slog ERROR "failed to pack lnxall_app."
		exit ${SEVAL}
	fi

	cd "${PACKDIR}"
	if [ $? -ne 0 ] ; then
		SEVAL=4
		slog ERROR "Failed to go to directory ${PACKDIR}"
		exit ${SEVAL}
	fi

	local err=0
	slog INFO "Compressing ${PACKFILE}..."
	if [ "${PLATFORM}" = "IMX6UL" ] ; then
		xz --flush-timeout=2 -4 -z ${PACKFILE}
		err=$?
	else
		xz --flush-timeout=3 -T 2 -4 -z ${PACKFILE}
		err=$?
	fi
	if [ $err -ne 0 ] ; then
		SEVAL=5
		slog ERROR "failed to compress ${PACKFILE}" 1>&2
		exit ${SEVAL}
	fi
	return 0
}

pack_gen() {
	cd "${PACKDIR}"
	if [ $? -ne 0 ] ; then
		SEVAL=1
		exit ${SEVAL}
	fi

	local ISSUE=$(sed -n -r -e 's/issue=(.+)/\1/p' /etc/lnxall-app-build-info.txt)
	[ -z "${ISSUE}" ] && ISSUE=unknown

	local ELF_OUT=''
	if [ "${EMS_IP}" = "${EMS_LOCALIP}" ] ; then
		ELF_OUT="LNXALL_APP_EMS_${PRODUCT_NAME}_$(date +%Y%m%d-%H%M%S)_${ISSUE}.elf"
	else
		ELF_OUT="LNXALL_APP_SLAVE_${PRODUCT_NAME}_$(date +%Y%m%d-%H%M%S)_${ISSUE}.elf"
	fi

	local ELF_BASE="${PACK_BDIR}/LNXALL_APP_${PLATFORM}.elf"
	if [ ! -f "${ELF_BASE}" ] ; then
		SEVAL=2
		slog ERROR "file not found: ${ELF_BASE}"
		exit ${SEVAL}
	fi

	slog INFO "Generating final image..."

	local TMP_COMMENT=$(mktemp)

	echo ": <<'COMMENT'" > "${TMP_COMMENT}"
	# 将build-info.txt的每一行添加为注释
	while IFS= read -r line; do
		echo "$line" >> "${TMP_COMMENT}"
	done < /etc/lnxall-app-build-info.txt
	echo "COMMENT" >> "${TMP_COMMENT}"
	# 合并注释和原始文件
	echo "#!/bin/bash" > "${ELF_OUT}"
	cat "${TMP_COMMENT}" "${ELF_BASE}" "${PACKDIR}/${PACKFILE}.xz" >> ${ELF_OUT}
	# 删除临时文件
	rm -f "${TMP_COMMENT}"

	if [ $? -ne 0 ] ; then
		SEVAL=3
		slog ERROR "failed to generate: \"${ELF_OUT}\""
		exit ${SEVAL}
	fi
	rm -rf *.xz *.tar # remove existing compressed files

	if [ "${EMS_IP}" = "${EMS_LOCALIP}" ] ; then
		slog INFO "Moving packed output to directory: ${EMS_DIR}"
		mv -f -v "${ELF_OUT}" "${EMS_DIR}/"
		SEVAL=$?
	else
		slog INFO "Copying packed output for $$"
		sshpass -p lnxall123 scp -oConnectTimeout=5 -oStrictHostKeyChecking=no \
			-oUserKnownHostsFile=/dev/null "${ELF_OUT}" "root@${EMS_IP}:${EMS_DIR}/"
		SEVAL=$?
	fi

	if [ ${SEVAL} -eq 0 ] ; then
		slog INFO "Application-packed-okay-$$, ${ELF_OUT}"
	else
		slog ERROR "failed to copy packed image to EMS: ${EMS_IP}"
	fi
	return 0
}

trap exithandler EXIT ABRT HUP INT TERM
slog INFO "Start lnxall packapp: $$"
pack_init
pack_app
pack_gen
exit $SEVAL
