# Quick Commander's plugins: build them, run their tests.

# sjasmplus (1.24 or newer): the one given in SJASMPLUS, else from PATH
sjasmplus := env("SJASMPLUS", `command -v sjasmplus || true`)

# build all the plugins into out/, made anew, their symbols, listings and SLDs beside (the tests', the coverage's): each folder
# with its <folder>.asm a plugin (common/ and testkit/ none),
# a folder's LINKS its links (each line a key: an empty file KEY.PLUGIN, the plugin the file its <folder>.asm's savebin
# writes: pts/LINKS's PT3._PT, PT2._PT and VT2._PT to the PT3, PT2 and VT2 player _PT)
build:
    #!/usr/bin/env sh
    set -e
    if [ -z "{{sjasmplus}}" ]; then
        echo "sjasmplus 1.24 or newer: put it in PATH or set SJASMPLUS" >&2
        exit 1
    fi
    rm -rf out
    mkdir out
    for d in */; do
        p=${d%/}
        [ -f "$p/$p.asm" ] || continue
        "{{sjasmplus}}" --nologo --msg=war --outprefix=out/ --sym="out/$p.sym" --lst="out/$p.lst" \
            --sld="out/$p.sld" --fullpath=rel "$p/$p.asm"
        if [ -f "$p/LINKS" ]; then
            P=$(sed -n 's/^[[:space:]]*savebin[[:space:]]*"\([^"]*\)".*/\1/p' "$p/$p.asm")
            [ -n "$P" ] && [ "$(printf '%s\n' "$P" | wc -l)" -eq 1 ] ||
                { echo "$p/$p.asm: a plugin with LINKS writes one file (savebin)" >&2; exit 1; }
            while read -r e; do : > "out/$e.$P"; done < "$p/LINKS"
        fi
    done
    ls -l out

# run the plugins' tests: the plugins built (just build), then go test (Go 1.26 or newer) on the kit's host (testkit),
# with no QC and nothing outside this folder; ARGS go to go test (just test -run KitFls -v)
test *ARGS:
    #!/usr/bin/env sh
    set -e
    just build > /dev/null
    PLUGINS_OUT="$(pwd)/out" go test -count=1 {{ARGS}} ./...

# the plugins' coverage by their tests: the share of each folder's instructions they run, of each plugin's (its own
# and the ones it includes); with LINES a folder (just coverage fls), its procedures and their lines not run
coverage LINES="":
    #!/usr/bin/env sh
    set -e
    just build > /dev/null
    counts=$(mktemp -d)
    trap 'rm -rf "$counts"' EXIT
    rc=0
    PLUGINS_OUT="$(pwd)/out" PLUGINS_COVER="$counts" go test -count=1 ./... > "$counts/test.txt" 2>&1 || rc=1
    if [ -n "{{LINES}}" ]; then
        go run ./testkit/coverage -lines "{{LINES}}" out "$counts" || rc=1
    else
        go run ./testkit/coverage out "$counts" "$counts/test.txt" || rc=1
    fi
    exit $rc

# remove out/
clean:
    rm -rf out
