#!/bin/sh
# Developed by Hashcore team

failure() {
	echo "$1"
	exit 1
}

fwinfo() {
	awk "/$1/ { print \$2 }" /etc/fw-info.json | tr -d '",'
}

if [ -f /etc/fw-info.json ]; then
	plat=$(fwinfo platform)
	inst_type=$(fwinfo install_type)

	if [ -n "$plat" ] && [ "$plat" != "xil" ]; then
		failure "Wrong firmware update file, target platform is xil"
	fi

	if [ -n "$inst_type" ] && [ "$inst_type" != "nand" ]; then
		failure "Wrong firmware update file, target installation type is nand"
	fi
fi

if [ ! -f sign-public.pem ] || [ ! -f sign-public.pem.sig ]; then
	echo "sign-public.pem or sign-public.pem.sig not found"
	exit 1
fi

if [ ! -f /etc/keys/master-public.pem ]; then
	echo "/etc/keys/master-public.pem not found"
	exit 1
fi

if [ ! -f uramdisk.image.gz ] || [ ! -f uramdisk.image.gz.sig ]; then
	echo "uramdisk.image.gz or uramdisk.image.gz.sig not found"
	exit 1
fi

if [ ! -f fw.md5 ] || [ ! -f fw.md5.sig ]; then
	echo "fw.md5 or fw.md5.sig not found"
	exit 1
fi

openssl dgst -sha256 -verify /etc/keys/master-public.pem \
	-signature sign-public.pem.sig sign-public.pem >/dev/null 2>&1

if [ $? -ne 0 ]; then
	echo "Invalid signature for sign-public.pem"
	exit 1
fi

for sig in *.sig; do
	file="${sig%.sig}"

	[ "$file" = "runme.sh" ] && continue
	[ "$file" = "sign-public.pem" ] && continue

	echo "Verifying signature for $file"
	openssl dgst -sha256 -verify "sign-public.pem" \
		-signature "$sig" "$file" >/dev/null 2>&1 || {
		echo "Invalid signature: $file"
		exit 1
	}
done

echo "All signatures are valid"
echo "Updating firmware"

echo "Verifying md5 checksums"
if ! md5sum -s -c fw.md5 >/dev/null 2>&1; then
	echo "MD5 checksum verification failed"
	exit 1
fi

echo "Updating uramdisk.image.gz"
flash_erase /dev/mtd1 0x0 0x100 >/dev/null 2>&1
nandwrite -p -s 0x0 /dev/mtd1 uramdisk.image.gz >/dev/null 2>&1

if ubiattach -d 4 -m 2; then
	mkdir -p /tmp/stock-config
	if mount -t ubifs ubi4_0 /tmp/stock-config; then
		if [ -e /tmp/stock-config/sn ]; then
			cp /tmp/stock-config/sn "/config/serial" || true
		fi
		umount /tmp/stock-config
	fi
	ubidetach -d 4
fi

sync
exit $?
