#!/bin/sh

if [[ -z $key ]]; then
	/bin/echo "Usage: sudo key=<update_key> -E update.sh"
	exit 1
fi

password=`/bin/cat /etc/update_key | /usr/bin/sha512sum | /usr/bin/cut -d' ' -f 1`
auth=`/bin/echo -n $key | /usr/bin/sha512sum | /usr/bin/cut -d' ' -f 1`                                                             

if [[ "$auth" != "$password" ]]; then
        /bin/echo "Wrong password"
        exit 1
fi


pubkey="/pub.pem"
file="/tmp/update.tgz.cc"
/bin/echo "### ccOS Update Script ###"
/bin/echo "[+] Starting"
/bin/sleep 1
/bin/echo "[+] Extracting Signature"
skip=$(expr $(stat -c '%s' $file) - 256)
if [[ -L $file ]]
then
	exit 0
fi 
/usr/bin/dd if=/tmp/update.tgz.cc of=sig bs=1 count=256 skip=$skip > /dev/null 2>&1
/usr/bin/truncate -s $skip update.tgz.cc
check=`/usr/bin/openssl dgst -sha256 -verify $pubkey -signature /tmp/sig /tmp/update.tgz.cc`
if [ "$check" == "Verified OK" ]
then
        /bin/echo "[+] Signature is valid!"
        /bin/echo "[+] Upgrading..."
        /usr/bin/tar -xvzf /tmp/update.tgz.cc -C /
        /bin/rm /tmp/update.tgz.cc /tmp/sig
        /bin/echo "[+] Done"
        exit 0
else
        /bin/echo "[-] Signature error, exiting..."
        /bin/rm /tmp/update.tgz.cc /tmp/sig
        exit 1
fi