#!/bin/sh

URL=http://ppa.linuxfactory.or.kr/mastering
IMAGE=android-odroidn2-20210930
TARGET=/dev/mmcblk0

BASEDIR=/tmp/mastering

function cleanup() {
	fw_setenv petitboot,mastering
}

function panic() {
	echo "E: $1"
	cleanup
	/usr/bin/figlet FAILED!!
	sleep 10
	exit 1
}

function reboot() {
	echo 1 > /proc/sys/kernel/sysrq
	echo b > /proc/sysrq-trigger
}

function wait_for_device() {
        n=1
        echo "W: waiting for "${1}"..."
        while [ ${n} -le 5 ]; do
                [ -e ${1} ] && return 0
                n=$((n + 1))
                sleep 1
        done

        return 1
}

function download() {
	wget ${1} -O ${2} \
		|| panic "failed to download ${1}"
}

# Obtain IP address
udhcpc

# Ensure the target device to flash is present
wait_for_device ${TARGET} || panic "device ${TARGET} not found"

mkdir -p ${BASEDIR}

# Take download details from a server
for f in BLKSIZE FILES MD5SUM; do
	download ${URL}/${IMAGE}/${f} ${BASEDIR}/${f}
done

BLKSIZE=$(cat ${BASEDIR}/BLKSIZE)

prev=$(fw_printenv -n petitboot,mastering 2>/dev/null)

for f in $(cat ${BASEDIR}/FILES); do
	next=$(echo ${f} | cut -d'.' -f2)

	if [ "x${prev}" != "x" ]; then
		[ $(expr ${next} \<= ${prev}) -eq 1 ] && continue
	fi

	download ${URL}/${IMAGE}/${f} ${BASEDIR}/${f}

	HASH1=$(md5sum ${BASEDIR}/${f} | awk '{print $1}')
	HASH2=$(cat ${BASEDIR}/MD5SUM | grep ${f} | awk '{print $1}')

	[ ${HASH1} = ${HASH2} ] \
		|| panic "${f} has invalid hash ${HASH1}, expected ${HASH2}"

	echo "zcat ${f} | dd conv=fsync bs=${BLKSIZE} seek=${next} of=${TARGET}"
	zcat ${BASEDIR}/${f} \
		| dd conv=fsync bs=${BLKSIZE} seek=${next} of=${TARGET} \
		|| panic "failed to flash a block with ${f}"

	fw_setenv petitboot,mastering ${next}
	prev=${next}

	rm -f ${BASEDIR}/${f}
done

cleanup

/usr/bin/figlet SUCCESS

sleep 5
reboot
