#!/bin/sh
# Regression for scripts/ngspice-hier-op: it must fold every block, label each
# state, write both seed forms, and never modify the user's deck.
#
# A shell test rather than a .cir because the tool DRIVES ngspice rather than
# being driven by it, so tests/bin/check.sh does not fit.

NG=${top_builddir:-../../..}/src/ngspice
TOOL=${top_srcdir:-../../..}/scripts/ngspice-hier-op
DECK=${srcdir:-.}/hier_op-1.cir

command -v python3 >/dev/null 2>&1 || { echo "python3 not found"; exit 77; }
[ -x "$NG" ] || { echo "no ngspice at $NG"; exit 77; }
[ -f "$TOOL" ] || { echo "no tool at $TOOL"; exit 77; }

WORK=`mktemp -d` || exit 1
trap 'rm -rf "$WORK"' EXIT
cp "$DECK" "$WORK/deck.cir" || exit 1
before=`cksum < "$WORK/deck.cir"`

( cd "$WORK" && python3 "$OLDPWD/$TOOL" deck.cir --ngspice "$OLDPWD/$NG" \
      --outdir out --min-devices 2 > run.log 2>&1 )
rc=$?

fail=0
if [ $rc -ne 0 ]; then
    echo "FAILED: tool exited $rc"; fail=1
fi
# the deck must come back byte-identical
if [ "`cksum < "$WORK/deck.cir"`" != "$before" ]; then
    echo "FAILED: the tool modified the user's deck"; fail=1
fi
# every block folded
if ! grep -q "still out   : none" "$WORK/run.log"; then
    echo "FAILED: not every block was folded"; fail=1
fi
# three folds, each labelled
n=`grep -c "^  folded " "$WORK/run.log"`
if [ "$n" -ne 3 ]; then
    echo "FAILED: expected 3 folded blocks, got $n"; fail=1
fi
if grep -q "\[both-failed" "$WORK/run.log"; then
    echo "FAILED: a block produced no state at all"; fail=1
fi
# every STEP state (not the intermediate __seed/__end files) must exist in both
# seed forms and carry nodes
for f in "$WORK"/out/base.ic "$WORK"/out/s1_*.ic "$WORK"/out/s2_*.ic "$WORK"/out/s3_*.ic; do
    case "$f" in *__*) continue ;; esac
    b=`echo "$f" | sed 's/\.ic$//'`
    [ -s "$f" ]          || { echo "FAILED: empty or missing $f"; fail=1; }
    [ -s "$b.nodeset" ]  || { echo "FAILED: empty or missing $b.nodeset"; fail=1; }
done
# the .nodeset must really be nodeset cards, not .ic (silent-seed trap)
if grep -q "^\.ic " "$WORK"/out/base.nodeset 2>/dev/null; then
    echo "FAILED: .nodeset file contains .ic cards"; fail=1
fi

[ $fail -eq 0 ] || { sed -n '1,40p' "$WORK/run.log"; exit 1; }
exit 0
