#!/bin/sh
#
#  This script bootstraps the configs repo on a machine that has no Fossil
#  installed while verifying everything against embedded hashes. The idea is to
#  have a single script that needs to be copied to the target machine and then
#  bootstraps everything in a trusted way.
# 

set -e
fossil_version="2.24"
fossil_sha512="7fc7de7d947b0946866df38c6cb2215f6452d31903cae6470bb4a692816b2803eb66ea372280256e5cd00759e4d02a0ae459de2f56f39af10e873579d53d33ee"
config_checkin="c86690c5919cdcbfc31ec23b7438039a43211055fc883e6013c2c8dd18aee922"

download_and_verify() {
	wget -O "$1" "$2"
	hash="$(openssl sha512 "$1" | cut -d' ' -f 2)"

	echo "Hash for $1:"
	echo "  Expected: $3"
	echo "  Got:      $hash"

	if test x"$hash" = x"$3"; then
		echo "Hash matches!"
	else
		echo "Hash doesn't match!"
		exit 1
	fi
}

download_and_verify "fossil-src-$fossil_version.tar.gz" "https://fossil-scm.org/home/tarball/version-$fossil_version/fossil-src-$fossil_version.tar.gz" "$fossil_sha512"

gunzip -c "fossil-src-$fossil_version.tar.gz" | tar xf -
cd "fossil-src-$fossil_version"
./configure --prefix="$HOME/.local"
if which gmake >/dev/null 2>&1; then
	gmake
	gmake install
else
	make
	make install
fi
cd ..

rm -fr "fossil-src-$fossil_version" "fossil-src-$fossil_version.tar.gz"

export PATH="$HOME/.local/bin:$PATH"

mkdir -p "$HOME/Devel/configs"
cd "$HOME/Devel/configs"
fossil clone https://fl.nil.im/configs configs.fossil
fossil open configs.fossil
fossil up "$config_checkin"
./setup.sh

cd "$HOME"
echo "export PATH=\"\$HOME/.local/bin:\$PATH\"" >>.zshenv
exec zsh -l
