#!/usr/bin/env bash

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly ROOT
readonly RESULTS="${ROOT}/results"
readonly IMAGE="serein-pers-01-persistence-mapping"

if [[ "${RESULTS}" != "${ROOT}/results" ]]; then
  echo "refusing to clear an unexpected results directory" >&2
  exit 65
fi

cd "${ROOT}"

milliseconds() {
  perl -MTime::HiRes=time -e 'printf "%.0f\n", time * 1000'
}

capture() {
  local name="$1"
  local expected_exit="$2"
  shift 2
  local directory="${RESULTS}/${name}"
  local started finished actual_exit

  mkdir -p "${directory}"
  {
    printf '%q' "$1"
    for argument in "${@:2}"; do
      printf ' %q' "${argument}"
    done
    printf '\n'
  } >"${directory}/command.txt"

  started="$(milliseconds)"
  set +e
  "$@" >"${directory}/output.txt.tmp" 2>&1
  actual_exit=$?
  set -e
  finished="$(milliseconds)"
  sed -E -e 's/[[:space:]]+$//' -e '${/^$/d;}' \
    "${directory}/output.txt.tmp" >"${directory}/output.txt"
  rm "${directory}/output.txt.tmp"
  {
    printf 'expected_exit_code=%s\n' "${expected_exit}"
    printf 'exit_code=%s\n' "${actual_exit}"
    printf 'duration_ms=%s\n' "$((finished - started))"
  } >"${directory}/metadata.txt"

  if [[ ${actual_exit} -ne ${expected_exit} ]]; then
    echo "FAILED: ${name} exited ${actual_exit}; expected ${expected_exit}" >&2
    return 1
  fi

  printf '%-52s exit %s as expected\n' "${name}" "${actual_exit}"
}

in_container() {
  docker run --rm --volume "${RESULTS}:/experiment/results" "${IMAGE}" "$@"
}

evidence_case() {
  local evidence_path="$1"
  local case_name="$2"
  docker run --rm \
    --volume "${RESULTS}/${evidence_path}:/artifacts" \
    --env "ARTIFACT_DIR=/artifacts" \
    "${IMAGE}" php tests/run.php "${case_name}"
}

mutant_case() {
  local mutation="$1"
  local case_name="$2"
  docker run --rm "${IMAGE}" sh -lc \
    "php mutate.php ${mutation} && php tests/run.php ${case_name}"
}

mutant_analysis() {
  local mutation="$1"
  docker run --rm "${IMAGE}" sh -lc \
    "php mutate.php ${mutation} && php analyze.php"
}

mutation_diff() {
  local mutation="$1"
  local path="$2"
  docker run --rm "${IMAGE}" sh -lc \
    "cp ${path} /tmp/original.php && php mutate.php ${mutation} >/dev/null && diff -u /tmp/original.php ${path}"
}

rm -rf \
  "${RESULTS}/analysis" \
  "${RESULTS}/behavior" \
  "${RESULTS}/diffs" \
  "${RESULTS}/environment" \
  "${RESULTS}/negative" \
  "${RESULTS}/setup" \
  "${RESULTS}/sources" \
  "${RESULTS}/verification"
mkdir -p "${RESULTS}"

capture setup/build 0 docker build --load --tag "${IMAGE}" .
capture environment/php 0 in_container php --version
capture environment/extensions 0 in_container php -m
capture sources/primary 0 in_container php source-evidence.php
capture analysis/inventory 0 in_container php analyze.php
capture behavior/full-suite 0 in_container php tests/run.php --all

for case_name in \
  mapped-round-trip child-removal atomic-save duplicate-order-number \
  lifecycle-constraint line-constraints foreign-key due-projection \
  query-plans domain-isolation
do
  capture "behavior/${case_name}" 0 \
    evidence_case "behavior/${case_name}" "${case_name}"
done

capture negative/drop-currency 1 \
  mutant_case drop-currency mapped-round-trip
capture negative/wrong-total 1 \
  mutant_case wrong-total mapped-round-trip
capture negative/skip-child-delete 1 \
  mutant_case skip-child-delete child-removal
capture negative/commit-root-early 1 \
  mutant_case commit-root-early atomic-save
capture negative/remove-order-number-unique 1 \
  mutant_case remove-order-number-unique duplicate-order-number
capture negative/remove-lifecycle-check 1 \
  mutant_case remove-lifecycle-check lifecycle-constraint
capture negative/remove-due-index 1 \
  mutant_case remove-due-index query-plans
capture negative/hydrate-due-projection 1 \
  mutant_analysis hydrate-due-projection
capture negative/leak-persistence-into-domain 1 \
  mutant_analysis leak-persistence-into-domain

capture diffs/drop-currency 1 \
  mutation_diff drop-currency src/OrderMapper.php
capture diffs/wrong-total 1 \
  mutation_diff wrong-total src/OrderMapper.php
capture diffs/skip-child-delete 1 \
  mutation_diff skip-child-delete src/SqliteOrders.php
capture diffs/commit-root-early 1 \
  mutation_diff commit-root-early src/SqliteOrders.php
capture diffs/remove-order-number-unique 1 \
  mutation_diff remove-order-number-unique src/Schema.php
capture diffs/remove-lifecycle-check 1 \
  mutation_diff remove-lifecycle-check src/Schema.php
capture diffs/remove-due-index 1 \
  mutation_diff remove-due-index src/Schema.php
capture diffs/hydrate-due-projection 1 \
  mutation_diff hydrate-due-projection src/FindOrdersDueForFulfilment.php
capture diffs/leak-persistence-into-domain 1 \
  mutation_diff leak-persistence-into-domain src/Domain/Order.php

capture verification/results 0 in_container php verify-results.php

echo "Evidence retained in ${RESULTS}"
