#! /bin/sh
# manual-update <compressed tarball>
# Logilin 2020 - All right reserved.

PARTITION_PREFIX="/dev/mmcblk0p"
BOOT_PARTITION_A=2
BOOT_PARTITION_B=3
BOARD_NAME_FILE="/etc/hytem-board-name"
UPDATE_MNT="/tmp/mnt"

EXIT_CODE_OK=0
EXIT_CODE_SYSTEM=1
EXIT_CODE_IMAGE=2

tarball="$1"

if ! /bin/mount /boot -o ro
then
	echo "Unable to mount /boot partition." >&2
	exit ${EXIT_CODE_SYSTEM}
fi

line=$(/sbin/fw_printenv current_boot)
if [ $? -eq 0 ]
then
        export $line
else
        current_boot=$(lsblk | grep 'part[[:blank:]]\+/$' | sed 's/^.*mmcblk.p\(.\).*$/\1/')
fi
/bin/umount /boot

if [ "${current_boot}" = "${BOOT_PARTITION_A}" ]
then
	new_boot="${BOOT_PARTITION_B}"
else
	new_boot="${BOOT_PARTITION_A}"
fi

partition="${PARTITION_PREFIX}${new_boot}"

if ! /bin/dd if=/dev/zero  of="${partition}" bs=1M count=32
then
	echo "Unable to wipeout ${partition}." >&2
	exit ${EXIT_CODE_SYSTEM}
fi

if ! /sbin/mkfs.ext2 "${partition}"
then
	echo "Unable to format ${partition}" >&2
	exit ${EXIT_CODE_SYSTEM}
fi

if [ -d "${UPDATE_MNT}" ]; then rm -rf "${UPDATE_MNT}" ; fi

if ! /bin/mkdir -p "${UPDATE_MNT}"
then
	echo "Unable to create ${UPDATE_MNT}" >&2
	exit ${EXIT_CODE_SYSTEM}
fi

if ! /bin/mount "${partition}" "${UPDATE_MNT}"
then
	echo "Unable to mount ${partition} on ${UPDATE_MNT}" >&2
	exit ${EXIT_CODE_SYSTEM}
fi

cd "${UPDATE_MNT}/"

if ! /bin/tar xf "${tarball}"
then
	echo "Error when extracting ${tarball}" >&2
	exit ${EXIT_CODE_IMAGE}
fi

if ! /usr/bin/diff "${BOARD_NAME_FILE}" "${UPDATE_MNT}${BOARD_NAME_FILE}"
then
	echo "${tarball} is not for this kind of board" >&2
	exit ${EXIT_CODE_IMAGE}
fi

cd /
/bin/umount "${UPDATE_MNT}"
rm -rf "${UPDATE_MNT}"

if ! /bin/mount /boot/ -o rw
then
	echo "Unable to mount /boot" >&2
	exit ${EXIT_CODE_SYSTEM}
fi
/sbin/fw_setenv boot_next_1 ${new_boot}
/sbin/fw_setenv boot_next_2 ${new_boot}
/sbin/fw_setenv boot_next_3 ${new_boot}
umount /boot/

rm -f "${tarball}"

exit ${EXIT_CODE_OK}
