#!/bin/sh
# doctest-lhs <file.lhs>
#
# Run doctest against a literate-Haskell applet, using the file's own
# `-- stack ...` directive and `{-# LANGUAGE ... #-}` pragmas so the
# invocation always matches what `run-cached-lhs` actually compiles.
#
# Peer to /usr/local/bin/run-cached-lhs; same directive-parsing
# shape so a maintainer reading both files recognises the pattern.

set -eu

if [ $# -lt 1 ]; then
  echo "usage: doctest-lhs <file.lhs>" >&2
  exit 64
fi

SRC=$1; shift

DIRECTIVE=$(awk '/^>?[[:space:]]*-- stack /{
  sub(/^>?[[:space:]]*-- stack[[:space:]]+/, "")
  print; exit
}' "$SRC")

if [ -z "$DIRECTIVE" ]; then
  echo "doctest-lhs: no '-- stack' directive found in $SRC" >&2
  exit 65
fi

RESOLVER_OPTS=$(printf '%s\n' "$DIRECTIVE" \
  | grep -oE -- '--(resolver|snapshot)[[:space:]]+\S+' \
  | tr '\n' ' ')
PACKAGE_OPTS=$(printf '%s\n' "$DIRECTIVE" \
  | grep -oE -- '--package[[:space:]]+\S+' \
  | tr '\n' ' ')

XFLAGS=$(grep -oE 'LANGUAGE[[:space:]]+[A-Za-z]+' "$SRC" \
  | awk '{print "-X" $2}' \
  | tr '\n' ' ')

# If the script enables the LiquidHaskell plugin via OPTIONS_GHC,
# doctest can't load it: LH prints "**** LIQUID: SAFE ..." during
# GHCi load, and doctest's stdout-capture treats that as a test
# failure. LH belongs to the build pipeline (run-cached-lhs), not
# to doctest. Solution: rewrite the OPTIONS_GHC line into an inert
# comment in a temp copy, doctest that. Same line numbering, so
# any doctest failure still points at the right source line.
TMPSRC=""
if grep -qE 'OPTIONS_GHC[[:space:]]+-fplugin=LiquidHaskell' "$SRC"; then
  TMPSRC=$(mktemp --suffix=.lhs)
  trap 'rm -f "$TMPSRC"' EXIT
  sed -E 's|\{-#[[:space:]]*OPTIONS_GHC[[:space:]]+-fplugin=LiquidHaskell[[:space:]]*#-\}|{- LH plugin stripped for doctest -}|' \
    "$SRC" > "$TMPSRC"
  RUNSRC=$TMPSRC
else
  RUNSRC=$SRC
fi

exec /home/venusia/.ghcup/bin/stack $RESOLVER_OPTS exec \
  $PACKAGE_OPTS --package doctest -- \
  doctest $XFLAGS "$RUNSRC" "$@"
