#!/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
if [[ "${OUTPUT}" != "${ROOT}/results/clean-export" ]]; then
  echo "refusing to replace an unexpected clean-export directory" >&2
  exit 65
fi
rm -rf "${OUTPUT}"
mkdir -p "${OUTPUT}"
printf 'git archive %q editorial/reproductions/ops-02 | tar -x\n' \
  "${COMMIT}" >"${OUTPUT}/command.txt"
git -C "${REPOSITORY}" archive "${COMMIT}" editorial/reproductions/ops-02 \
  | tar -x -C "${TEMPORARY}"
EXPORTED="${TEMPORARY}/editorial/reproductions/ops-02"
readonly EXPORTED

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"
if [[ ${exit_code} -ne 0 ]]; then
  printf 'Clean export failed at %s\n' "${COMMIT}" >&2
  exit "${exit_code}"
fi

sha256() { shasum -a 256 "$1" | awk '{print $1}'; }
{
  printf 'resolved_commit=%s\n' "${COMMIT}"
  printf 'profile_sha256=%s\n' "$(sha256 "${EXPORTED}/results/profile.json")"
  printf 'decision_sha256=%s\n' "$(sha256 "${EXPORTED}/results/decisions/state-carriers.json")"
  printf 'source_evidence_sha256=%s\n' "$(sha256 "${EXPORTED}/results/sources/primary.json")"
  printf 'source_manifest_sha256=%s\n' "$(sha256 "${EXPORTED}/results/provenance/source-manifest.json")"
  printf 'mutation_count=%s\n' \
    "$(find "${EXPORTED}/results/mutations" -name 'MUT-*.diff' -type f | wc -l | tr -d ' ')"
  printf 'mutation_23_sha256=%s\n' \
    "$(sha256 "${EXPORTED}/results/mutations/MUT-23.diff")"
  printf 'exit_code=%s\n' "${exit_code}"
} >"${OUTPUT}/metadata.txt"
printf 'Clean export verified at %s\n' "${COMMIT}"
