#!/usr/bin/env bash
set -Eeuo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")/.."

fail=0
if git ls-files --error-unmatch .env >/dev/null 2>&1; then
  echo 'ERROR: .env is tracked.' >&2
  fail=1
fi
if git ls-files | grep -E '(^|/)(\.env|.*\.key|.*\.pem)$' >/tmp/clinic-sensitive-files.txt; then
  echo 'ERROR: sensitive files are tracked:' >&2
  cat /tmp/clinic-sensitive-files.txt >&2
  fail=1
fi
if grep -RInE "(DB_PASSWORD|TENANT_ADMIN_DB_PASSWORD|AWS_SECRET_ACCESS_KEY|MAIL_PASSWORD)\s*=\s*[^$[:space:]]+" . \
  --exclude-dir=.git --exclude-dir=vendor --exclude-dir=storage --exclude='*.example' --exclude='security_audit.sh' >/tmp/clinic-secret-matches.txt; then
  echo 'ERROR: possible hard-coded secret found:' >&2
  cat /tmp/clinic-secret-matches.txt >&2
  fail=1
fi

php artisan config:clear --env=testing >/dev/null
php artisan route:list --json >/dev/null
php artisan about >/dev/null

if (( fail )); then exit 1; fi
echo 'Security audit passed.'
