#!/usr/bin/env bash
#
# Exercises the honeypot and timing checks in save-report.php.
#
# Run this against your STAGING subdomain, not production —
# see the README for why.
#
# Usage:
#   ./test-security-checks.sh https://test.hashava.org
#
# Requires: curl
#
set -euo pipefail

BASE_URL="${1:-}"
if [ -z "$BASE_URL" ]; then
    echo "Usage: $0 <base-url>"
    echo "Example: $0 https://test.hashava.org"
    exit 1
fi

COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

fetch_form_tokens() {
    # Loads report.php fresh (new cookie jar each time, so each
    # scenario gets its own session and its own form-issued timestamp)
    # and pulls out the csrf token and cookie.
    rm -f "$COOKIE_JAR"
    curl -s -c "$COOKIE_JAR" \
        "$BASE_URL/report.php?type=found" \
        | grep -oE 'name="csrf_token" value="[^"]+"' \
        | sed -E 's/.*value="([^"]+)".*/\1/'
}

post_report() {
    local csrf="$1"
    local website_value="$2"
    curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" \
        -b "$COOKIE_JAR" \
        -X POST "$BASE_URL/save-report.php" \
        --data-urlencode "type=found" \
        --data-urlencode "lang=en" \
        --data-urlencode "csrf_token=$csrf" \
        --data-urlencode "submission_timezone=Asia/Jerusalem" \
        --data-urlencode "story=I found a brown bag of candy near the shuk yesterday." \
        --data-urlencode "contact_name=Test Runner" \
        --data-urlencode "contact_phone=0500000000" \
        --data-urlencode "contact_email=" \
        --data-urlencode "contact_instructions=" \
        --data-urlencode "website=$website_value"
}

echo "== Scenario 1: normal submission (should pass, no flag) =="
csrf="$(fetch_form_tokens)"
sleep 3
post_report "$csrf" ""
echo

echo "== Scenario 2: honeypot filled (should flag: honeypot_filled) =="
csrf="$(fetch_form_tokens)"
sleep 3
post_report "$csrf" "http://example.com"
echo

echo "== Scenario 3: submitted immediately (should flag: submitted_too_fast) =="
csrf="$(fetch_form_tokens)"
post_report "$csrf" ""
echo

echo "All three scenarios saved a report either way (by design — see README)."
echo "Check your PHP error log now for two lines starting 'Hashava security"
echo "event:' — one for honeypot_filled, one for submitted_too_fast. There"
echo "should be no such line for scenario 1."
