#!/bin/sh
# run-cached-lhs <file.lhs>
#
# Compile-and-cache wrapper for literate-Haskell applets. Reads the
# file's own `-- stack ...` directive for resolver and packages,
# hashes mtime+size as a cache key, and execs the cached binary
# directly on hit. On miss, compiles via `stack ghc` (the
# LiquidHaskell plugin, when enabled via OPTIONS_GHC, runs inside
# that step), then atomically caches the result.
#
# Peer to /usr/local/bin/doctest-lhs; same directive-parsing awk so
# both files extract the same flag set from the same source.

set -eu
SRC=$1; shift
CACHE=/var/cache/venusia-compiled
mkdir -p "$CACHE"
KEY=$(stat -c '%Y-%s' "$SRC")
BIN="$CACHE/$(basename "$SRC" .lhs).$KEY"
if [ ! -x "$BIN" ]; then
  OPTS=$(awk '/^>?[[:space:]]*-- stack /{
    sub(/^>?[[:space:]]*-- stack[[:space:]]+/, "")
    print; exit
  }' "$SRC" | grep -oE -- '--(resolver|snapshot|package)[[:space:]]+\S+' | tr '\n' ' ')
  TMP=$(mktemp -d)
  trap "rm -rf '$TMP'" EXIT
  /home/venusia/.ghcup/bin/stack ghc $OPTS -- \
    -O -dynamic -outputdir "$TMP" "$SRC" -o "$BIN.tmp" >&2
  mv "$BIN.tmp" "$BIN"
fi
exec "$BIN" "$@"
