#!/bin/bash

abort_push() {
	echo "$@" >&2
	echo "Push aborted." >&2
	popd > /dev/null
	exit 1
}

# Hooks are always executed from .git/hooks
ROOT_DIR="$(git rev-parse --show-toplevel)"
pushd $ROOT_DIR > /dev/null || \
	abort_push "Failed to change to the project root!"


# Check Java files for non-ASCII characters.
echo ":: Running pre-push Java source check ::"
LC_ALL=C git grep -n -e '[^[:cntrl:] -~]' -- ':/*.java'
[ $? -eq 1 ] || \
	abort_push "Check failed: Java sources contain non-ASCII characters!"

echo "Java source check passed."
echo ""


# Check that the source code is well formatted.
echo ":: Running pre-push format check ::"

"$ROOT_DIR/tools/sbt/bin/sbt" renaissanceFormatCheck || \
	abort_push "Check failed: code is not well-formatted. Run 'sbt renaissanceFormat'!"

echo "Format check passed."
echo ""


# Check that README.md is up-to-date.
echo ":: Running pre-push markdown check ::"

RENAISSANCE_GIT_VERSION=$(git describe --abbrev=7 --dirty=-SNAPSHOT)
RENAISSANCE_VERSION=${RENAISSANCE_GIT_VERSION#v}

java -jar "$ROOT_DIR/target/renaissance-gpl-$RENAISSANCE_VERSION.jar" --readme || \
	abort_push "Check failed: unable to launch Renaissance!"

git diff --exit-code -- README.md || \
	abort_push "Check failed: README.md is outdated!"

echo "Markdown check passed."
echo ""


echo "Pre-push checks successful."
popd > /dev/null
