#! /bin/bash -e

CERT_PUB="${CERT_PUB-"/usr/share/upgrade-script/pub.crt"}"

FILEPATH="${FILEPATH-$(ls -1 /var/lib/updown/downloads/*.dsu | tail -n1)}"

HEAD="$(tail -c 10 "${FILEPATH}")"

if [ "${HEAD:4:10}" != "DESIUP" ]; then
	echo "wrong header string" >&2 
	echo -n "${HEAD}" | hexdump -C
	exit 1
fi

SIZE="${HEAD:0:4}"

if ! [[ ${SIZE} =~ ^[0-9]+$ ]]; then
	echo "invalid header size" >&2 
	echo -n "${SIZE}" | hexdump -C
	exit 1
fi

openssl dgst -sha256 -verify <(openssl x509 -in "${CERT_PUB}" -pubkey -noout) -signature <( \
	tail -c $(( 10#$SIZE + 10 )) "${FILEPATH}" | head -c-10) <( head -c-$(( 10#$SIZE + 10 )) "${FILEPATH}" \
	)  || { echo "signature wrong" >&2 ; exit 1; }

TMP="$(mktemp -d)"

sudo modprobe fuse

echo "mounting $FILEPATH (this might take a while)"
squashfuse "${FILEPATH}" "${TMP}"

if [ -x "${TMP}/upgrade.sh" ]; then
	echo "executing ${TMP}/upgrade.sh"
	${TMP}/upgrade.sh "${TMP}"
else
	echo "installing packages"
	sudo dpkg -i -E "${TMP}/"*.deb
fi

echo "finished"
fusermount -uz "${TMP}"
rmdir "${TMP}"
