#!/bin/bash
#
# analyze.sh -- run the DJGPP build under gcc's -fanalyzer.
#
# Usage:
#   ./analyze.sh         # analyse the whole build (slow: 2-5x)
#   ./analyze.sh 2>&1 | tee analyze.log
#
# How it works:
#
# The project Makefiles hardcode -Werror in CFLAGS.  gcc evaluates
# diagnostic flags in order, so a trailing -Wno-error (appended
# AFTER CFLAGS at compile time) demotes analyzer findings back to
# warnings -- otherwise the first analyzer hit aborts the build.
#
# We do that by setting CC to a wrapper that execs the real compiler
# with -fanalyzer prepended and -Wno-error appended.  make -k keeps
# building after individual failures so we see every hit in one run.
#
# Runs the existing top-level Makefile with an override CC; no
# Makefile edits required.  Output goes to stderr; redirect with
# '2>&1 | tee analyze.log' to capture.

set -u

cd "$(dirname "$0")"

REAL_CC="$HOME/djgpp/djgpp/bin/i586-pc-msdosdjgpp-gcc"

if [ ! -x "$REAL_CC" ]; then
    echo "analyze.sh: $REAL_CC not executable" >&2
    exit 1
fi

# Build the wrapper in a temp dir that the spawned makes can see.
WRAP_DIR="$(mktemp -d)"
trap 'rm -rf "$WRAP_DIR"' EXIT
WRAP="$WRAP_DIR/analyze-cc"

cat > "$WRAP" <<WRAPEOF
#!/bin/bash
exec "$REAL_CC" -fanalyzer "\$@" -Wno-error
WRAPEOF

chmod +x "$WRAP"

echo "analyze.sh: running full build under gcc -fanalyzer..." >&2
echo "analyze.sh: this will be slow (2-5x normal build time)." >&2

# -k = keep going after errors so we collect every analyzer hit
# CC=... overrides the assignment in each submakefile
make -k CC="$WRAP" 2>&1

echo "analyze.sh: done.  Grep for 'Wanalyzer' to see findings." >&2
