#!/usr/bin/env bash
# misc_br_inferred_cwd — cross-terminal cwd resolution.
# Step 1: run `verify` from one directory with a RELATIVE model
# path, with NUC_RUN_LOG pointing at our tempdir.
# Step 2: run `bug-report --yes --include-source` from a DIFFERENT
# directory; the inference must read the LOG's cwd to resolve the
# relative model path. If resolution were against bug-report's
# cwd, parse -E would fail with "no such file".
set -euo pipefail

# Set up the "user's project" with a relative-pathed model.
proj="$NUCTEST_TMPDIR/proj"
mkdir -p "$proj"
cat > "$proj/Foo.dzn" <<'EOF'
interface IFoo { in void e(); behavior { on e: {} } }
component Foo { provides IFoo p; behavior { on p.e(): {} } }
EOF

# Step 1: prime last-run.log from inside $proj using a RELATIVE
# path "Foo.dzn".
run_log="$NUCTEST_TMPDIR/last-run.log"
( cd "$proj" && \
  NUC_RUN_LOG="$run_log" "$NUCLEOS" verify -k -m Foo Foo.dzn > /dev/null 2>&1 )
grep -q '^cwd' "$run_log" || { echo "FAIL: last-run.log missing cwd"; exit 1; }
grep -q '^argv' "$run_log" || { echo "FAIL: last-run.log missing argv"; exit 1; }

# Step 2: run bug-report from a DIFFERENT cwd (the misc-test
# tempdir, $NUCTEST_TMPDIR itself, not $proj). Inference must
# read the log's cwd = $proj and resolve "Foo.dzn" → $proj/Foo.dzn.
cd "$NUCTEST_TMPDIR"
NUC_RUN_LOG="$run_log" "$NUCLEOS" bug-report \
    --yes --include-source --no-last-panic \
    -o "$NUCTEST_TMPDIR/bug.tar.gz" < /dev/null \
    > "$NUCTEST_TMPDIR/out.txt" 2> "$NUCTEST_TMPDIR/err.txt"

if ! tar tzf "$NUCTEST_TMPDIR/bug.tar.gz" | grep -q '/model/model\.flat\.anon\.dzn$'; then
    echo "FAIL: archive missing model/model.flat.anon.dzn" >&2
    echo "(this would happen if bug-report resolved 'Foo.dzn' against its OWN cwd,)" >&2
    echo "(instead of the log's cwd $proj)" >&2
    cat "$NUCTEST_TMPDIR/err.txt" >&2
    tar tzf "$NUCTEST_TMPDIR/bug.tar.gz" >&2
    exit 1
fi
