#!/bin/bash

set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
URL="${1:-http://127.0.0.1:7703}"

echo "Testing security headers at $URL"
echo "======================================"

# Function to check if a header exists and print its value
check_header() {
    local endpoint="$1"
    local header="$2"
    local expected="$3"
    
    echo ""
    echo "Testing $header on $endpoint"
    
    # Get headers using curl -I (HEAD request) or curl -i (for full response)
    response=$(curl -s -I "$URL$endpoint" 2>/dev/null || curl -s -i -X GET "$URL$endpoint" 2>/dev/null | head -n 20)
    
    # Check if header exists (case-insensitive)
    if echo "$response" | grep -qi "^$header:"; then
        value=$(echo "$response" | grep -i "^$header:" | sed 's/[^:]*: *//' | tr -d '\r\n')
        echo "  ✓ Found: $value"
        if [ ! -z "$expected" ] && [ "$value" != "$expected" ]; then
            echo "    WARNING: Expected '$expected'"
        fi
    else
        echo "  ✗ Missing $header"
        return 1
    fi
}

# Test endpoints
echo ""
echo "1. Testing /status endpoint (no auth required)"
echo "-----------------------------------------------"
check_header "/status" "X-Frame-Options" "DENY"
check_header "/status" "X-Content-Type-Options" "nosniff"
check_header "/status" "X-XSS-Protection" "1; mode=block"
check_header "/status" "Content-Security-Policy" ""
check_header "/status" "Referrer-Policy" "strict-origin-when-cross-origin"
check_header "/status" "Permissions-Policy" ""

echo ""
echo "2. Testing / endpoint (welcome page)"
echo "-------------------------------------"
check_header "/" "X-Frame-Options" "DENY"
check_header "/" "X-Content-Type-Options" "nosniff"

echo ""
echo "3. Testing authenticated endpoint /dir"
echo "---------------------------------------"
response=$(curl -s -i "$URL/dir" 2>/dev/null | head -n 30)
echo "$response" | grep -E "^(X-Frame-Options|X-Content-Type-Options|X-XSS-Protection|Content-Security-Policy|Referrer-Policy|Permissions-Policy):" || echo "Headers shown above"

echo ""
echo "4. Testing error response (404)"
echo "--------------------------------"
response=$(curl -s -i "$URL/nonexistent" 2>/dev/null | head -n 30)
echo "$response" | grep -E "^(X-Frame-Options|X-Content-Type-Options|X-XSS-Protection|Content-Security-Policy|Referrer-Policy|Permissions-Policy):" || echo "Headers shown above"

echo ""
echo "======================================"
echo "Security headers test complete"