#!/usr/bin/env bash
set -Eeuo pipefail
set -x

PREFIX='/srv/ci/$PROJECT'
mkdir -p "${DOLLAR}PREFIX"
read -r _ SHA _ # oldrev newrev refname
FILENAME="${DOLLAR}(date -Is)-${DOLLAR}SHA.log"
LOGFILE="${DOLLAR}PREFIX/${DOLLAR}FILENAME"
exec &> >(tee -a "${DOLLAR}LOGFILE")

echo "Starting CI job at: ${DOLLAR}(date -Is)"

finish() {
  STATUS="${DOLLAR}?"
  printf "\n\n>>> exit status was %s\n" "${DOLLAR}STATUS"
  echo "Finishing CI job at: ${DOLLAR}(date -Is)"
  popd
  NOTE=$(cat <<EOF
See CI logs with:
  git notes --ref=refs/notes/ci-logs show ${DOLLAR}SHA
  git notes --ref=refs/notes/ci-data show ${DOLLAR}SHA
EOF
)
  git notes --ref=refs/notes/ci-data add -f -m "${DOLLAR}STATUS ${DOLLAR}FILENAME"
  git notes --ref=refs/notes/ci-logs add -f -F "${DOLLAR}LOGFILE"
  git notes append -m "${DOLLAR}NOTE"
  printf "\n\n>>> CI logs added as Git note."
}
trap finish EXIT

unset GIT_DIR
CLONE="${DOLLAR}(mktemp -d)"
git clone . "${DOLLAR}CLONE"
pushd "${DOLLAR}CLONE"
git config --global user.email git@euandre.org
git config --global user.name 'EuAndreh CI'

./scripts/with-container.sh '${AUTOTOOLS_SETUP}make clean check public'
rm -rf /srv/http/$PROJECT/ && mv public/ /srv/http/$PROJECT/
