#!/usr/bin/env sh
set -u

script_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
root="${1:-$(CDPATH= cd -- "$script_dir/../.." && pwd)}"
start="$(date +%s)"
tmp="${TMPDIR:-/tmp}/panopainter-renderer-boundary-$$.txt"

find "$root/src" -type f \( -name '*.c' -o -name '*.cc' -o -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) | while IFS= read -r file; do
    rel="${file#"$root"/}"
    case "$rel" in
        src/renderer_gl/*|src/rtt.cpp|src/texture.cpp)
            continue
            ;;
    esac
    awk -v rel="$rel" '
        /^[[:space:]]*\/\// { next }
        match($0, /\<(GL|WGL)_[A-Z0-9_]+\>/) {
            print rel ":" FNR ":" substr($0, RSTART, RLENGTH)
        }
    ' "$file"
done > "$tmp"

count="$(wc -l < "$tmp" | tr -d '[:space:]')"
end="$(date +%s)"
elapsed_ms="$(( (end - start) * 1000 ))"
exit_code="0"
if [ "$count" -ne 0 ]; then
    exit_code="1"
fi

printf '{"command":"check-renderer-boundary","exitCode":%s,"violationCount":%s,"elapsedMs":%s}\n' "$exit_code" "$count" "$elapsed_ms"
rm -f "$tmp"
exit "$exit_code"
