#!/bin/bash
#
# cppcheck.sh -- static analysis for the DVX source tree.
#
# Usage:
#   ./cppcheck.sh                     # whole tree
#   ./cppcheck.sh src/widgets         # one subtree
#   ./cppcheck.sh src/libs/kpunch/texthelp/textHelp.c   # one file
#
# Exits 0 even when warnings are found -- cppcheck's exit status is
# not useful as a gate for this codebase (too many DJGPP-isms it can't
# resolve).  Read the output.

set -e

cd "$(dirname "$0")"

TARGETS="${@:-src}"

INCLUDES=(
    -Isrc/libs/kpunch/libdvx
    -Isrc/libs/kpunch/libdvx/platform
    -Isrc/libs/kpunch/libdvx/thirdparty
    -Isrc/libs/kpunch/libtasks
    -Isrc/libs/kpunch/texthelp
    -Isrc/libs/kpunch/listhelp
    -Isrc/libs/kpunch/dvxshell
    -Isrc/libs/kpunch/taskmgr
    -Isrc/libs/kpunch/serial
    -Isrc/widgets/kpunch
    -Isrc/apps/kpunch/dvxbasic
    -Isrc/apps/kpunch/dvxbasic/compiler
    -Isrc/apps/kpunch/dvxbasic/runtime
    -Isrc/apps/kpunch/dvxbasic/formrt
)

# DJGPP / platform macros cppcheck can't find.  Expand them to nothing
# so the preprocessor leaves the code visible to the analyser instead
# of eliding whole functions behind unknown macro calls.
DEFINES=(
    -DDXE_EXPORT=
    -DDVX_WIDGET_IMPL
    -D__DJGPP__=2
)

# Suppressions: things cppcheck flags that aren't actually wrong for
# this codebase.  Keep the list short so real issues stay visible.
SUPPRESS=(
    --suppress=missingIncludeSystem       # system headers aren't on host
    --suppress=unusedFunction             # many public exports look "unused" to a .c-only scan
    --suppress=constParameterPointer      # noisy on this style
    --suppress=constVariablePointer       # ditto
    --suppress=normalCheckLevelMaxBranches
    # stb_ds arrput is a macro -- cppcheck can't see that the value
    # (including heap pointers inside it) is stored, so it reports
    # spurious null-derefs on the stb_ds dynamic-array handle.
    --suppress=nullPointerRedundantCheck
    --suppress=nullPointerArithmeticRedundantCheck
    # Thirdparty headers -- their own style isn't our problem.
    --suppress='*:src/libs/kpunch/libdvx/thirdparty/*'
    --suppress='*:src/libs/kpunch/sql/thirdparty/*'
)

exec cppcheck \
    --enable=warning,style,performance,portability \
    --inline-suppr \
    --std=c99 \
    --platform=unix32 \
    --quiet \
    -j"$(nproc)" \
    -i src/libs/kpunch/sql/thirdparty \
    -i src/libs/kpunch/libdvx/thirdparty \
    "${INCLUDES[@]}" \
    "${DEFINES[@]}" \
    "${SUPPRESS[@]}" \
    $TARGETS
