#!/usr/bin/env bash

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REPOSITORY="$(git -C "${ROOT}" rev-parse --show-toplevel)"
COMMIT="${1:-HEAD}"
RESOLVED_COMMIT="$(git -C "${REPOSITORY}" rev-parse "${COMMIT}^{commit}")"
OUTPUT="${ROOT}/results/clean-export"
TEMPORARY="$(mktemp -d)"
readonly ROOT REPOSITORY COMMIT RESOLVED_COMMIT OUTPUT TEMPORARY

cleanup() {
  if [[ -n "${TEMPORARY}" && -d "${TEMPORARY}" ]]; then
    rm -rf "${TEMPORARY}"
  fi
}
trap cleanup EXIT

mkdir -p "${OUTPUT}"
printf 'git archive %q editorial/reproductions/leg-01 | tar -x\n' \
  "${RESOLVED_COMMIT}" >"${OUTPUT}/command.txt"

git -C "${REPOSITORY}" archive \
  "${RESOLVED_COMMIT}" editorial/reproductions/leg-01 \
  | tar -x -C "${TEMPORARY}"

EXPORTED="${TEMPORARY}/editorial/reproductions/leg-01"
readonly EXPORTED

"${EXPORTED}/run.sh" >"${OUTPUT}/output.txt.tmp" 2>&1

compare() {
  local relative="$1"
  local label="$2"
  local clean_hash
  local working_hash

  clean_hash="$(sha256sum "${EXPORTED}/${relative}" | cut -d' ' -f1)"
  working_hash="$(sha256sum "${ROOT}/${relative}" | cut -d' ' -f1)"

  if [[ "${clean_hash}" != "${working_hash}" ]]; then
    echo "clean ${label} differs from retained evidence" >&2
    exit 1
  fi

  printf '%s_sha256=%s\n' "${label}" "${clean_hash}"
}

{
  printf 'resolved_commit=%s\n' "${RESOLVED_COMMIT}"
  compare results/verification/results/output.txt verifier
  compare results/positive/observations/output.txt observations
  compare results/analysis/inventory/output.txt analysis
  compare results/diffs/reorder-diagnostic-trace/output.txt trace_diff
  compare \
    results/diffs/reorder-independent-calculations/output.txt \
    call_order_diff
  compare results/diffs/round-insurance-down/output.txt rounding_diff
  printf 'exit_code=0\n'
} >"${OUTPUT}/metadata.txt"

sed -E -e 's/[[:space:]]+$//' -e '${/^$/d;}' \
  "${OUTPUT}/output.txt.tmp" >"${OUTPUT}/output.txt"
rm "${OUTPUT}/output.txt.tmp"

echo "Clean export verified at ${RESOLVED_COMMIT}"
