#!/bin/sh
set -eu
umask 077
usage() {
  echo "Usage: sh trialloom-ci.sh check REVISION REPOSITORY_PATH RESULT.json" >&2
  echo "       sh trialloom-ci.sh publish RESULT.json TOKEN_FILE" >&2
  exit 2
}
site=https://trialloom.com
case "${1-}" in
  check-manifest)
    [ "$#" -eq 5 ] || usage
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    curl -fsS --max-time 30 "$site/capsule-ci/manifest-ci-8db92c9f0493.py" -o "$tmp/manifest-ci.py"
    (cd "$tmp" && echo '8db92c9f04935f9ad2ebba88e8a06b23c8b2327fdaa4bbc07539c980c364f142  manifest-ci.py' | sha256sum -c)
    python3 -I "$tmp/manifest-ci.py" "$2" "$3" "$4" "$5"
    ;;
  check)
    [ "$#" -eq 4 ] || usage
    commit=$(git rev-parse --verify --end-of-options "$2^{commit}")
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    git cat-file blob "$commit:$3" > "$tmp/candidate.py"
    curl -fsS --retry 2 --max-time 60 "$site/capsule-ci/rerun-87adcbf3072a.py" -o "$tmp/rerun.py"
    curl -fsS --retry 2 --max-time 60 "$site/repair-3/trial-capsule.zip" -o "$tmp/capsule.zip"
    (cd "$tmp" && echo '87adcbf3072a5991c09f09c2b5de33984d5657919227be2ef226de7142fe9414  rerun.py' | sha256sum -c)
    python3 -I "$tmp/rerun.py" --capsule "$tmp/capsule.zip" --candidate "$tmp/candidate.py" --out "$tmp/result.json"
    python3 -I - "$tmp/result.json" "$commit" "$4" <<'PY'
import json, os, pathlib, sys, tempfile, uuid
source, revision, destination = sys.argv[1:]
record = json.loads(pathlib.Path(source).read_bytes())
record.update(revision=revision, run='git.' + uuid.uuid4().hex)
with tempfile.NamedTemporaryFile(mode='w', dir=pathlib.Path(destination).parent, delete=False) as out:
    json.dump(record, out)
os.replace(out.name, destination)
PY
    ;;
  publish)
    [ "$#" -eq 3 ] || usage
    # Feed the credential through stdin so it stays out of process arguments.
    token=$(cat "$3")
    printf 'Authorization: Bearer %s\n' "$token" | curl -fsS --retry 2 --max-time 30 \
      -H @- -H 'Content-Type: application/json' --data-binary "@$2" "$site/ci-results/upload"
    python3 -I - "$2" <<'PY'
import json, pathlib, sys
r = json.loads(pathlib.Path(sys.argv[1]).read_bytes())
passed = r['status'] == 'complete' and r['wrong'] == 0 and r.get('triangle', True) is True
print('Published result for', r['revision'], '·', 'passed' if passed else r['status'] if r['status'] == 'blocked' else 'failed')
sys.exit(0 if passed else 1)
PY
    ;;
  *) usage ;;
esac
