#!/usr/bin/env bash
# A stand-in for nix, so the end-to-end check can exercise pure checks.
#
# The pure transfer rule is closure-digest equality, and a real nix cannot
# run inside a nix build — there is no daemon in the sandbox. So this stub
# stands in for the evaluator, and it models exactly the property the rule
# depends on: a check's input closure is the content of the files it reads.
#
# A check named <name> declares what it reads in checks/<name>.inputs, one
# path per line. Evaluating it writes a derivation listing the SHA-256 of
# every file beneath those paths; nix-store (the sibling stub) turns that
# list into the closure attest digests. Change a file the check reads and
# the closure moves; change anything else and it does not.
#
# Everything downstream of the evaluation is the real thing: attest builds
# the manifest and the digest, and the integrator compares them.
set -euo pipefail

# A scenario that needs something to happen while a pass is working names
# it here. Evaluating a check is the middle of a pass — after the requests
# are read and before anything lands — so the stand-in runs it then.
if [ -n "${VALLEY_E2E_DURING_PASS:-}" ]; then
  sh -c "$VALLEY_E2E_DURING_PASS"
fi

store="${VALLEY_FAKE_STORE:?VALLEY_FAKE_STORE is not set}"
mkdir -p "$store"

# A scenario that counts what is asked of the evaluator names a log, and
# each call is written to it as one line: "eval shared <attr>…" for attest's
# shared evaluation, "eval <attr>" for one check alone, "eval attrNames"
# for the list of checks, and "build" for a build.
log() {
  if [ -n "${VALLEY_E2E_NIX_LOG:-}" ]; then printf '%s\n' "$*" >> "$VALLEY_E2E_NIX_LOG"; fi
}

# derive <tree> <attr>: evaluate one check, writing its derivation into the
# store and printing the derivation's path. A check that declares a
# failure (checks/<name>.fails) or an output it shares with other checks
# (checks/<name>.output, as fixed-output derivations can) carries that
# beside its derivation, for the build. A check that declares an error no
# evaluation can catch (checks/<name>.uncaught) fails with what it declares.
derive() {
  local tree="$1" attr="$2" list drv path f
  list="$tree/checks/$attr.inputs"
  if [ -f "$tree/checks/$attr.uncaught" ]; then
    cat "$tree/checks/$attr.uncaught" >&2
    return 1
  fi
  [ -f "$list" ] || { echo "nix (stub): $tree declares no check $attr" >&2; return 1; }
  drv="$(mktemp "$store/$attr-XXXXXX.drv")"
  while read -r path; do
    [ -n "$path" ] || continue
    while IFS= read -r f; do
      printf '%s %s\n' "$(sha256sum < "$f" | cut -d' ' -f1)" "${f#"$tree"/}" >> "$drv"
    done < <(find "$tree/$path" -type f | LC_ALL=C sort)
  done < "$list"
  [ -s "$drv" ] || { echo "nix (stub): check $attr reads nothing" >&2; return 1; }
  if [ -f "$tree/checks/$attr.fails" ]; then cp "$tree/checks/$attr.fails" "$drv.fails"; fi
  if [ -f "$tree/checks/$attr.output" ]; then
    printf '%s/%s.out\n' "$store" "$(cat "$tree/checks/$attr.output")" > "$drv.output"
  fi
  printf '%s' "$drv"
}

case "${1:-}" in
  eval)
    # The flake reference is the one argument naming a check attribute,
    # and --apply, when given, is followed by the expression applied.
    spec="" apply="" prev=""
    for a in "$@"; do
      case "$a" in *'#checks.'*) spec="$a" ;; esac
      [ "$prev" != --apply ] || apply="$a"
      prev="$a"
    done
    [ -n "$spec" ] || { echo "nix (stub): no #checks. reference in: $*" >&2; exit 2; }
    tree="${spec%%#*}"
    rest="${spec#*#checks.}"
    if [ "$rest" = "${rest%.drvPath}" ] && [ "$apply" = builtins.attrNames ]; then
      # `nix eval --json --apply builtins.attrNames …#checks.<system>`:
      # every check the tree declares.
      log eval attrNames
      names=""
      for f in "$tree"/checks/*.inputs; do
        [ -e "$f" ] || continue
        n="$(basename "$f" .inputs)"
        names="${names:+$names,}\"$n\""
      done
      printf '[%s]\n' "$names"
      exit 0
    fi
    if [ "$rest" = "${rest%.drvPath}" ]; then
      # attest's shared evaluation, `nix eval --json --apply <expression>
      # …#checks.<system>`: the derivation of every check the expression
      # names, each as a quoted string, and null for a check that does not
      # evaluate. An error no evaluation can catch ends the whole of it, as
      # a type error ends nix's.
      attrs=()
      while IFS= read -r quoted; do
        attrs+=("${quoted//\"/}")
      done < <(grep -o '"[^"]*"' <<< "$apply")
      log eval shared "${attrs[@]}"
      for attr in "${attrs[@]}"; do
        if [ -f "$tree/checks/$attr.uncaught" ]; then
          cat "$tree/checks/$attr.uncaught" >&2
          exit 1
        fi
      done
      out=""
      for attr in "${attrs[@]}"; do
        if drv="$(derive "$tree" "$attr" 2> /dev/null)"; then
          value="\"$drv\""
        else
          value=null
        fi
        out="${out:+$out,}\"$attr\":$value"
      done
      printf '{%s}\n' "$out"
      exit 0
    fi
    attr="${rest#*.}"
    log eval "${attr%.drvPath}"
    derive "$tree" "${attr%.drvPath}"
    ;;
  build)
    # `nix build --no-link --print-out-paths <drv>^*`: every derivation
    # named, each to its one output, where the nix-store stub finds it. The
    # output is a function of the derivation, as a build's output ought to
    # be, or, when checks share it, of its name. A check that declares a
    # failure fails with what it declares, on standard error, and builds
    # nothing.
    log build
    status=0
    for a in "$@"; do
      case "$a" in
        *.drv^*)
          drv="${a%^*}"
          if [ ! -f "$drv" ]; then
            echo "nix (stub): no such derivation: $drv" >&2
            status=1
            continue
          fi
          if [ -f "$drv.fails" ]; then
            cat "$drv.fails" >&2
            status=1
            continue
          fi
          # Written beside the store and moved into place, so two builds
          # of one output at once leave it whole, as nix's locks do.
          if [ -f "$drv.output" ]; then
            out="$(cat "$drv.output")"
            mkdir -p "$out"
            tmp="$(mktemp "$store/.result-XXXXXX")"
            basename "$out" .out > "$tmp"
          else
            out="${drv%.drv}.out"
            mkdir -p "$out"
            tmp="$(mktemp "$store/.result-XXXXXX")"
            cp "$drv" "$tmp"
          fi
          mv -f "$tmp" "$out/result"
          printf '%s\n' "$out"
          ;;
      esac
    done
    exit "$status"
    ;;
  *)
    echo "nix (stub): unsupported command: ${1:-}" >&2
    exit 2
    ;;
esac
