#!/usr/bin/env bash
# Smoke test: login as a role, hit every GET route, report non-200 responses.
# Usage: bash tests/smoke.sh <username> [password]
set -u
BASE="http://127.0.0.1:8088"
USER="${1:-superadmin}"
PASS="${2:-Uji#Coba2026}"
JAR="/tmp/ck_${USER}.txt"
OUT="/tmp/smoke_${USER}.log"
rm -f "$JAR" "$OUT"

TOKEN=$(curl -s -c "$JAR" "$BASE/masuk" | grep -oE 'name="_token" value="[^"]+"' | head -1 | sed 's/.*value="//;s/"//')
CODE=$(curl -s -b "$JAR" -c "$JAR" -o /dev/null -w "%{http_code}" -X POST "$BASE/masuk" \
        --data-urlencode "_token=$TOKEN" --data-urlencode "username=$USER" --data-urlencode "password=$PASS")
if [ "$CODE" != "302" ]; then echo "LOGIN GAGAL ($USER) http=$CODE"; exit 1; fi
echo "== LOGIN OK: $USER =="

FAIL=0; TOTAL=0; DENIED=0
while IFS= read -r URL; do
  [ -z "$URL" ] && continue
  TOTAL=$((TOTAL+1))
  BODY="/tmp/b.html"
  HTTP=$(curl -s -b "$JAR" -c "$JAR" -o "$BODY" -w "%{http_code}" "$BASE$URL")
  ERR=""
  if grep -qiE "Fatal error|Parse error|Uncaught|Warning</b>|Notice</b>|SQLSTATE" "$BODY" 2>/dev/null; then
    ERR=$(grep -oiE "(Fatal error|Parse error|Uncaught [A-Za-z\\\\]+|SQLSTATE\[[0-9A-Z]+\])[^<]{0,160}" "$BODY" | head -1)
  fi
  case "$HTTP" in
    200|302) if [ -n "$ERR" ]; then echo "PHP-ERR $HTTP $URL :: $ERR" | tee -a "$OUT"; FAIL=$((FAIL+1)); fi ;;
    403)     DENIED=$((DENIED+1)) ;;
    *)       echo "HTTP$HTTP $URL ${ERR:+:: $ERR}" | tee -a "$OUT"; FAIL=$((FAIL+1)) ;;
  esac
done < "$(dirname "$0")/urls.txt"

echo "== $USER: total=$TOTAL gagal=$FAIL ditolak403=$DENIED =="
exit 0
