#!/bin/bash
# searph syntax gate - run before every push/deploy.
# Luau is the executor language (https://luau.org): Lua 5.1 base, gradual typing,
# string interpolation, compound assignment. Plain `lua`/`luajit` can NOT parse it,
# so this gate uses the real luau-compile in parse-only mode.
set -u
cd "$(dirname "$0")"

LUAU=""
for cand in ../.tools/luau-bin/luau-compile luau-compile; do
	if command -v "$cand" > /dev/null 2>&1; then
		LUAU="$cand"
		break
	fi
done

fail=0

if [ -n "$LUAU" ]; then
	echo "luau-compile: $LUAU"
	for f in *.lua; do
		# --only-parse = full Luau parser, no codegen. Exit 0 = syntactically valid.
		if "$LUAU" --only-parse "$f" > /dev/null 2>&1; then
			echo "OK    $f"
		else
			echo "FAIL  $f"
			"$LUAU" --only-parse "$f" 2>&1 | head -5
			fail=1
		fi
	done
else
	echo "SKIP  luau-compile not found (install from https://github.com/luau-lang/luau/releases)"
	fail=1
fi

for f in *.js; do
	if command -v node > /dev/null 2>&1; then
		if node --check "$f" > /dev/null 2>&1; then
			echo "OK    $f"
		else
			echo "FAIL  $f"
			node --check "$f" 2>&1 | head -5
			fail=1
		fi
	else
		echo "SKIP  $f (node not installed)"
	fi
done

# secrets must never ship: any hit below is a hard failure
# code files only: docs may name the prefixes
if grep -rE -n 'glpat-|cfut_|private_token=' --include='*.lua' --include='*.js' . > /tmp/searph-secrets.txt 2>/dev/null; then
	echo "FAIL  secret-like strings found:"
	head -10 /tmp/searph-secrets.txt
	fail=1
fi
rm -f /tmp/searph-secrets.txt

if [ "$fail" -ne 0 ]; then
	echo "SYNTAX GATE: FAIL"
	exit 1
fi
echo "SYNTAX GATE: PASS"
