#!/bin/sh

UPGRADE_OPTION="$1"
THIS_SCRIPT="$(readlink -f $0)"
TARGET_DIR="/tmp/wl2004_newver_files"
SYSTEM_FILE="/tmp/wl2004_newver_files/wl2004_kernel_update.elf"

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="/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
}

main() {
	rm -rf /tmp/wl2004_newver_files
	extract_to_tmp
	if [ $? -ne 0 ] ; then
		echo "Error, failed to extract files."
		return 2
	fi

	if [ ! -d "$TARGET_DIR" ] ; then
		echo "Error, '$TARGET_DIR' not exist"
		return 3
	fi

	file_count=$(find "$TARGET_DIR" -maxdepth 1 -type f ! -name ".*" 2>/dev/null | wc -l)
	if [ $file_count -ne 2 ] ; then
		echo "Error, '$file_count' files in '$TARGET_DIR'"
		return 4
	fi

	files_path=$(find "$TARGET_DIR" -maxdepth 1 -type f ! -name ".*" ! -name "$SYSTEM_FILE" -print -quit 2>/dev/null)
	if [ -z "$files_path" ] || [ ! -f "$files_path" ] ; then
		echo "Error, failed to find application.elf"
		return 5
	fi

	check_md5sum "$SYSTEM_FILE" 47de35393f10325477e583cb978dfb5d
	[ $? -ne 0 ] && return 6

	if [ -f ${THIS_SCRIPT} ] ; then 
		echo "Info, delete '${THIS_SCRIPT}'"
		nothup bash -c "rm -f '${THIS_SCRIPT}'"
		sync
	fi

	chmod +x "$SYSTEM_FILE"
	"$SYSTEM_FILE"
	if [ $? -ne 0 ] ; then
		echo "Error, '$SYSTEM_FILE' failed to upgrade"
		return 7
	fi

	chmod +x "$files_path"
	if [ "$UPGRADE_OPTION" = "-n" ] ; then
		"$files_path" -n
	else
		"$files_path"
	fi
	rm -rf /tmp/wl2004_newver_files
	return 0
}

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

main
exit $?
#  RAW_DATA_BEGIN #####################
