#!/bin/sh

export PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ '
export HOME=/home/midipix

if [ -z "$SYSROOT" ]; then
	echo '$SYSROOT is not set!'
	exit 2
else
	mkdir -p "$SYSROOT" || exit 2
fi

tarballs=$(ls /updates/*.tar.gz 2>/dev/null)

if [ "$tarballs" = '/updates/*.tar.gz' ]; then
	exit 0
fi

for tarball in $tarballs; do
	tarball="${tarball##*/}"

	echo @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
	echo extracting files from /updates/$tarball
	echo ..................................................
	tar -xpvf /updates/$tarball -C "$SYSROOT" || exit 2

	echo archiving old $tarball
	echo ..................................................

	if [ -f /tarballs/$tarball ]; then
		pkgsig=$(sha256sum /tarballs/$tarball)
		pkgsig=${pkgsig%% *}
		pkgdir=/tarballs/archive/${tarball%%.tar.gz}/$pkgsig/
		mkdir -p $pkgdir
		mv /tarballs/$tarball $pkgdir
	fi

	echo caching the current $tarball
	echo ..................................................
	mv /updates/$tarball        /tarballs/
	mv /updates/$tarball.sha256 /tarballs/

	echo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	echo
done

rm -f /updates/update.pending

echo
echo
echo !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
echo Congrats! All tarballs were successfully extracted.
echo !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
