#!/usr/bin/env bash
#
# run_magic_valgrind.sh -- run magic under valgrind, straight from the build tree.
# Generated by configure from scripts/run_magic_valgrind.sh.in.
#
# PURPOSE
#   Memory-check the just-built magic without `make install`.  Stages
#   ${builddir}/CAD_DIR (symlinks) on first run, exports CAD_ROOT, then runs
#   valgrind on the self-contained "magicexec".
#
# USAGE
#   ./run_magic_valgrind.sh [valgrind-opts...] [-- [magic-args...]]
#
#   A "--" separates valgrind's own options from magic's:
#       ./run_magic_valgrind.sh                       # default memcheck options
#       ./run_magic_valgrind.sh foo.mag               # no "--" => all args go to magic
#       ./run_magic_valgrind.sh -v -- foo.mag         # valgrind -v, magic gets foo.mag
#       ./run_magic_valgrind.sh --tool=callgrind --   # a different valgrind tool
#   With no "--", every argument is passed to magic (the common case).
#
#   This checks the GUI binary; Tk/X allocations make the output noisy, so for
#   real leak hunting run the batch device:  ./run_magic_valgrind.sh -- -dnull
#
# ENVIRONMENT OVERRIDES (all optional; each wins over the baked default)
#   VALGRIND       valgrind binary to use (default: valgrind on PATH)
#   VALGRIND_OPTS  default valgrind options (default: --leak-check=full
#                  --error-exitcode=0).  Set empty to clear them; command-line
#                  options before "--" are added after these.
#   CAD_ROOT    reuse an alternate runtime tree instead of staging $builddir/CAD_DIR
#   MAGIC_WISH  wish for the Tk console (default: the configure-matched wish)
#   WISH TCLSH  wish/tclsh matching this build's Tcl/Tk (--with-tk / --with-tcl)
#   MAGIC_BUILDDIR MAGIC_SRCDIR  build/source tops (default: baked-in absolutes)
#   Inherited values are sanity-checked; problems print as stderr warnings.
#   See magic_run_common.sh for the authoritative list and defaults.
set -eu
here="$(cd "$(dirname "$0")" && pwd)"
. "$here/magic_run_common.sh"

VALGRIND="${VALGRIND:-valgrind}"
command -v "$VALGRIND" >/dev/null 2>&1 || magic_warn "valgrind '$VALGRIND' not found on PATH"
VALGRIND_OPTS="${VALGRIND_OPTS---leak-check=full --error-exitcode=0}"

magic_require_built
magic_stage
magic_split_args "$@"

# valgrind <opts> magicexec -- <magic-args>
exec "$VALGRIND" $VALGRIND_OPTS \
    ${MAGIC_TOOL_OPTS[@]+"${MAGIC_TOOL_OPTS[@]}"} \
    "$MAGIC_TCL/magicexec" -- \
    ${MAGIC_ARGS[@]+"${MAGIC_ARGS[@]}"}
