#!/bin/sh

BLKDEV=/dev/mmcblk1boot0
UBOOT_MD5='1afa6b0fddc41a0b6656c44663607f86'
SRCBIN="$(readlink -f $0)"

verify_system() {
	if [ "$(uname -m)" != 'armv7l' ] ; then
		echo "Error, not target IMX6UL device." 1>&2
		return 1
	fi

	if [ -z "$(grep -e 'Freescale i.MX6 Ultralite' /proc/cpuinfo)" ] ; then
		echo "Error, not target IMX6UL device." 1>&2
		return 2
	fi

	if [ ! -b ${BLKDEV} ] ; then
		echo "Error, block device not found: /dev/mmcblk1boot0" 1>&2
		return 3
	fi
	return 0
}

check_kernel() {
	if [ ! -e '/dev/mem' ] ; then
		echo "Warning, please upgrade IMX6UL kernel: /dev/mem not found." 1>&2
	fi
	return 0
}

check_uboot() {
	cd /root || return 1
	rm -rf u-boot.bin ; sleep 1
	dd "if=${BLKDEV}" bs=512 skip=2 of=u-boot.bin count=838

	local md5="$(md5sum u-boot.bin | awk '{print $1}')"
	if [ "${md5}" = "${UBOOT_MD5}" ] ; then
		echo "U-boot has already been upgraded."
		check_kernel
		return 2
	fi

	echo "Will Upgrade u-boot shortly."
	return 0
}

unpack_binary() {
	cd /tmp || return 1
	# 88: the next line number after EBGIN_OF_DATA
	tail -n +88 "${SRCBIN}" | gzip -d -c | tar -x -f -
	if [ $? -ne 0 ] ; then
		echo "Error, failed to extract from binary" 1>&2
		return 2
	fi

	local md5="$(md5sum u-boot.imx | awk '{print $1}')"
	if [ "${md5}" != "${UBOOT_MD5}" ] ; then
		rm -rf u-boot.imx mmap
		echo "Error, u-boot.imx has corrupted." 1>&2
		return 3
	fi

	if [ -e mmap ] ; then
		mv -f -v mmap /usr/bin/
		chmod 755 /usr/bin/mmap
	fi

	echo 0 > /sys/block/mmcblk1boot0/force_ro
	dd if=u-boot.imx of=${BLKDEV} bs=512 seek=2 conv=notrunc
	echo "u-boot for IMX6UL has been upgraded: $?"
	echo 1 > /sys/block/mmcblk1boot0/force_ro
	rm -rf u-boot.imx ; sync
	check_kernel
	return 0
}

export PATH=/usr/bin:/usr/sbin:/bin:/sbin
if [ ! -f "${SRCBIN}" ] ; then
	echo "Error, source binary not found." 1>&2
	exit 1
fi
verify_system || exit 2
check_uboot || exit 3
unpack_binary || exit 4
exit 0
############################### BEGIN_OF_DATA
