#!/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" != "bb" ]; then
		failure "Wrong firmware update file, target platform is bb"
	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 devicetree.dtb ] || [ ! -f devicetree.dtb.sig ]; then
	echo "devicetree.dtb or devicetree.dtb.sig not found"
	exit 1
fi

if [ ! -f uImage ] || [ ! -f uImage.sig ]; then
	echo "uImage or uImage.sig 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"

if [ ! -d /mnt/nvdata/anthillos ]; then
	echo "AnthillOS not installed!"
	exit 1
fi

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 devicetree.dtb"
cp -f devicetree.dtb /mnt/nvdata/anthillos >/dev/null 2>&1

echo "Updating uImage"
cp -f uImage /mnt/nvdata/anthillos >/dev/null 2>&1

echo "Updating uramdisk.image.gz"
cp -f uramdisk.image.gz /mnt/nvdata/anthillos >/dev/null 2>&1

mkdir -p /tmp/stock-config
if mount -t jffs2 /dev/mtdblock9 /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

sync
exit $?
