#!/usr/bin/env bash

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REPOSITORY="$(git -C "${ROOT}" rev-parse --show-toplevel)"
COMMIT="$(git -C "${REPOSITORY}" rev-parse "${1:-HEAD}^{commit}")"
OUTPUT="${ROOT}/results/clean-export"
TEMPORARY="$(mktemp -d)"
readonly ROOT REPOSITORY COMMIT OUTPUT TEMPORARY
trap 'rm -rf "${TEMPORARY}"' EXIT
rm -rf "${OUTPUT}"
mkdir -p "${OUTPUT}"
printf 'git archive %q editorial/reproductions/ops-05 | tar -x\n' \
  "${COMMIT}" >"${OUTPUT}/command.txt"
git -C "${REPOSITORY}" archive "${COMMIT}" editorial/reproductions/ops-05 \
  | tar -x -C "${TEMPORARY}"
EXPORTED="${TEMPORARY}/editorial/reproductions/ops-05"
set +e
"${EXPORTED}/run.sh" >"${OUTPUT}/output.txt.tmp" 2>&1
exit_code=$?
set -e
sed -E -e 's/[[:space:]]+$//' -e '${/^$/d;}' \
  "${OUTPUT}/output.txt.tmp" >"${OUTPUT}/output.txt"
rm "${OUTPUT}/output.txt.tmp"
[[ ${exit_code} -eq 0 ]] || exit "${exit_code}"
{
  printf 'resolved_commit=%s\n' "${COMMIT}"
  printf 'summary_sha256=%s\n' \
    "$(shasum -a 256 "${EXPORTED}/results/summary.json" | awk '{print $1}')"
  printf 'source_evidence_sha256=%s\n' \
    "$(shasum -a 256 "${EXPORTED}/results/sources/primary.json" | awk '{print $1}')"
  printf 'exit_code=%s\n' "${exit_code}"
} >"${OUTPUT}/metadata.txt"
printf 'Clean export verified at %s\n' "${COMMIT}"
