#!/bin/bash
# install this by: cp ./.githooks/pre-commit .git/hooks/pre-commit

KEEP_TESTS=5
WORKTREE_DIR="$PWD"
TIMEOUT_SECS=10
MEMORY_KB=16777216
TEST_PREFIX=".tests-"

cd "$WORKTREE_DIR"
find -name "${TEST_PREFIX}*" -type d | sort -n | head -n -$KEEP_TESTS | xargs -r rm -r

export GIT_AUTHOR_DATE="${GIT_AUTHOR_DATE:-$(awk 'BEGIN {srand(); print srand()}')}"
test_dir="${TEST_PREFIX}${GIT_AUTHOR_DATE% +*}"

last=$(find -name "${TEST_PREFIX}*" -type d | sort -rn | head -n 1)
if [[ "$last" ]]; then
    mkdir -p "$test_dir/target"
    cp -rl "$last/target/" "$test_dir/"
fi

git archive "$(git write-tree)" --prefix="$test_dir/" | tar xf -
cd "$test_dir"

#TODO: globbing on branch names
buildscript=$(rgrep -l "branch:$(git branch --show-current)" .cehci/)

echo "buildscript = $buildscript"

if [[ "$buildscript" ]]; then
    ulimit -S -v $MEMORY_KB -t $TIMEOUT_SECS
    bash "$buildscript" | tee test.log
    exit $(tail -1 test.log)
fi
