#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"

printf '1/5 PHP syntax...\n'
while IFS= read -r -d '' file; do
  php -l "$file" >/dev/null
done < <(find "$ROOT" -type f -name '*.php' -print0)

printf '2/5 Pure function tests...\n'
php "$ROOT/tests/pure_functions.php"

printf '3/5 Executables in uploads/assets...\n'
if find "$ROOT/uploads" "$ROOT/assets" -type f \( -iname '*.php' -o -iname '*.phtml' -o -iname '*.phar' -o -iname '*.cgi' -o -iname '*.pl' \) | grep -q .; then
  echo 'Executable file found under uploads/assets.' >&2
  exit 1
fi

printf '4/5 Suspicious execution primitives...\n'
if grep -RInE --include='*.php' '\beval[[:space:]]*\(|\bassert[[:space:]]*\(|base64_decode[[:space:]]*\(|gzinflate[[:space:]]*\(|shell_exec[[:space:]]*\(|passthru[[:space:]]*\(|proc_open[[:space:]]*\(' "$ROOT" | grep -v '/tests/run_static_checks.sh' | grep -q .; then
  echo 'Suspicious execution primitive found.' >&2
  exit 1
fi

printf '5/5 Embedded production password marker...\n'
if grep -RIn --exclude='run_static_checks.sh' --exclude='INSTALLATION_AR.md' --exclude='config.local.php' "CHANGE_ME_AFTER_ROTATION" "$ROOT" >/dev/null; then
  :
fi
if grep -RIn --include='*.php' "{h\*++d&Pr4m8" "$ROOT" | grep -q .; then
  echo 'Original database password is still embedded.' >&2
  exit 1
fi

printf 'All static checks passed.\n'
