#!/bin/bash
BASE=http://127.0.0.1:8123
TA=65e11fc2f02718a68728f3e5c5642306   # lift A (326)
TB=5472a9d343281e1b19d7590a51a9dc23   # lift B (327)
pass=0; fail=0
chk () { # name expected actual
  if [ "$2" = "$3" ]; then echo "OK   $1 = $3"; pass=$((pass+1)); else echo "FAIL $1 expected=$2 got=$3"; fail=$((fail+1)); fi
}

# 1) 三份附件全部可下載
for id in 17 18 19; do
  code=$(curl -s -o dl_$id.pdf -w "%{http_code}" "$BASE/lift-card.php?k=$TA&file=$id")
  ctype=$(curl -s -D - -o /dev/null "$BASE/lift-card.php?k=$TA&file=$id" | grep -i '^content-type' | tr -d '\r')
  chk "doc$id http" 200 "$code"
  echo "     $ctype  size=$(stat -c%s dl_$id.pdf)"
done

# 2) 憑證 A 攞唔到 B 嘅附件
chk "cross-lift file=20 with tokenA" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=$TA&file=20")"
# 3) 憑證 B 攞唔到 A 嘅附件
chk "cross-lift file=19 with tokenB" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=$TB&file=19")"
# 4) 亂寫 id／0／負數
chk "file=999999" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=$TA&file=999999")"
chk "file=0" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=$TA&file=0")"
chk "file=abc" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=$TA&file=abc")"
# 5) 憑證格式／缺失
chk "no token" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php")"
chk "short token" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=abc")"
chk "uppercase token" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=$(echo $TA | tr 'a-f' 'A-F')")"
chk "sql-ish token" 404 "$(curl -s -o /dev/null -w '%{http_code}' --get --data-urlencode "k=' OR 1=1--" "$BASE/lift-card.php")"
# 6) 免登入：唔 should 唔 make 用者 page 先至攞到（對比受保護嘅 api）
chk "card page no session" 200 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/lift-card.php?k=$TA")"
chk "api lift-doc-list no session" 401 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api.php?action=lift-doc-list&id=326")"
chk "api lift-license no session" 401 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api.php?action=lift-license-docx&lift=326&contact=30")"
# 7) robots / noindex
hdr=$(curl -s -D - -o /dev/null "$BASE/lift-card.php?k=$TA" | grep -i 'x-robots-tag' | tr -d '\r')
echo "     $hdr"
echo "PASS=$pass FAIL=$fail"
