#!/bin/sh

# Created by jiaqiang.ye@lnxall.com
# 20250729

if [ -d '/opt/lnxall_app/bin' ] ; then
	export PATH=/opt/lnxall_app/bin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin
else
	export PATH=/lib/dyiot/bin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin
fi

BO_GWSN="$1"
THIS_SCRIPT="$(readlink -f $0)"
[ -z "${THIS_SCRIPT}" ] && THIS_SCRIPT="$0"

is_rocky() {
	if [ "$(uname -m)" != "x86_64" ] ; then
		echo "Error, invalid platform: $(uname -a)"
		return 1
	fi
	if [ ! -f /etc/os-release ] ; then
		echo "Error, os-release file not found"
		return 2
	fi

	if [ -z "$(grep -i -e rocky /etc/os-release)" ] ; then
		echo "Error, not rocky platform"
		return 3
	fi
	if [ ! -f /usr/bin/start_browser.sh ] ; then
		echo "Error, start_browser.sh not found."
		return 4
	fi
	return 0
}

check_md5sum() {
	if [ ! -f "$1" ] ; then
		echo "Warning, file not found: $1"
		return 1
	fi
	local md5=$(md5sum "$1" | awk '{print $1}')
	if [ "${md5}" != "$2" ] ; then
		echo "Warning, invalid MD5 for '$1', expected: $2, got ${md5}"
		return 2
	fi
	return 0
}

extract_to_tmp() {
	local tdir="$1"
	[ -z "${tdir}" ] && tdir=/tmp

	local line_no=$(cat -n "${THIS_SCRIPT}" | grep -a -E -e '#\s+RAW_DATA_BEGIN' | awk '{print $1}')
	if [ -z "${line_no}" ] ; then
		echo "Error, failed to get raw data line NO. => ${BO_GWSN}"
		return 1
	fi
	line_no=$((line_no + 1))

	tail -n "+${line_no}" "${THIS_SCRIPT}" | bzip2 -d -c | tar -x -f - -C "${tdir}"
	[ $? -eq 0 ] && return 0

	echo "Error, failed to extract file '${THIS_SCRIPT}' to ${tdir}"
	return 2
}

actual_work() {
	local MD5VAL=02a557c3068c301f91bf1416c049b785
	check_md5sum /usr/bin/start_browser.sh ${MD5VAL}
	if [ $? -eq 0 ] ; then
		echo "Already updated, skipped."
		return 0
	fi

	rm -rf /tmp/update_files
	extract_to_tmp
	if [ $? -eq 0 ] ; then
		cd /tmp/update_files
		check_md5sum start_browser.sh ${MD5VAL}
		[ $? -eq 0 ] && chmod 755 start_browser.sh && mv -v -f start_browser.sh /usr/bin/
		gsettings set org.gnome.desktop.a11y.keyboard enable true
		gsettings set org.gnome.desktop.a11y.applications screen-keyboard-enabled false
	fi
	cd /tmp && rm -rf update_files
	rm -rf "${THIS_SCRIPT}"
}

if [ ! -f "${THIS_SCRIPT}" ] ; then
	echo "Error, THIS SCRIPT not found: ${BO_GWSN}"
	exit 1
fi

if is_rocky ; then
	actual_work
	exit $?
fi
exit 0
#  RAW_DATA_BEGIN #####################
BZh91AY&SYR _Ȱmyg\
 @ݰ%CFOCF Sh(d     z@&M4ddт0F I L4#SMAƦC!=CC8P0%D TP(@rP@V@bXy4c)֢Cl^$"hp$9J示Dl-5l36|Z!#c`;_sI{4G)N_3vKbO-ǤfO,WMPCy(YMs.]BP8Eשd5)$P|6`0|lZa)sA`0ԇa4UA(uuHaNXzU(\JxBVwe# $V]FG$0$Nvkfs7|zCxpi=Fᗉ%ڮkкSdTόJα)cn$
0s`#fJu%@5{J*_,",	mC<E5	ZT>-x؋$/eÑ4	,Hk9!ZBBP_hJAmVLSC"1Qx#,TEh"xI*C3搘ZԼ1N%dܪ*P\<;vZָaJ1ql"&# "(H)Co}