#!/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" != "cv" ]; then
		failure "Wrong firmware update file, target platform is cv"
	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 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

find . -type f -name "*.sig" | while read -r 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 /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

if [ -d scripts ]; then
	echo "Updating scripts"
	cp -R -f scripts /nvdata/anthillos >/dev/null 2>&1
	chmod 4755 /nvdata/anthillos/scripts/boot
	chmod 755 /nvdata/anthillos/scripts/bootos.sh
	chmod 755 /nvdata/anthillos/scripts/updateos.sh
fi

if [ -e overlay.tar.gz ]; then
	echo "Updating overlay.tar.gz"
	cp -f overlay.tar.gz /nvdata/anthillos >/dev/null 2>&1
fi

mkdir -p /tmp/stock-config
if mount -t ext4 -o sync /dev/mmcblk0p5 /tmp/stock-config; then
	if [ -e /tmp/stock-config/sn ]; then
		cp /tmp/stock-config/sn /config/serial
	fi
	umount /tmp/stock-config
fi

if [ -f /nvdata/anthillos/scripts/updateos.sh ]; then
	nohup /nvdata/anthillos/scripts/updateos.sh >/dev/null 2>&1 &
fi

sync
exit $?
