#!/usr/bin/env bash
#
# onx-modsec-audit-event-detail — Tek event_id için full request/response.
#
# Input: {"event_id":"AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"}
# Output: {"request_headers","request_body","response_headers","all_matched_rules":[...]}

set -euo pipefail

readonly LOG_FILE="/var/log/httpd/modsec_audit.log"

input="$(cat)"
event_id="$(echo "$input" | jq -r '.event_id // empty')"

if [[ -z "$event_id" ]]; then
    jq -nc '{ok:false,error:"event_id required"}' >&2
    exit 1
fi

# event_id sanity (alphanumeric + hyphen)
if ! [[ "$event_id" =~ ^[A-Za-z0-9_-]{8,64}$ ]]; then
    jq -nc '{ok:false,error:"invalid event_id format"}' >&2
    exit 1
fi

if [[ ! -r "$LOG_FILE" ]]; then
    jq -nc '{ok:false,error:"audit log not readable"}' >&2
    exit 2
fi

# Find the block for this event_id (Serial format)
# Block starts at "--ABCDEFGH-A--" line containing event_id and ends at "--ABCDEFGH-Z--"
block=$(awk -v eid="$event_id" '
    $0 ~ "^--[A-Za-z0-9-]+--A--$" { capture = 0; buf = $0 "\n"; next }
    $0 ~ "^--[A-Za-z0-9-]+--Z--$" { if (capture) { print buf $0; exit } buf = ""; next }
    {
        buf = buf $0 "\n"
        if ($0 ~ eid) capture = 1
    }
' "$LOG_FILE" 2>/dev/null)

if [[ -z "$block" ]]; then
    jq -nc --arg eid "$event_id" '{ok:false,error:"event not found in log",event_id:$eid}' >&2
    exit 2
fi

# Extract sections (B = request headers, I = request body, F = response headers, H = ModSec messages)
request_headers=$(echo "$block" | awk '/--B--/,/--C--|--I--|--F--/' | head -n -1 | tail -n +2)
request_body=$(echo "$block"    | awk '/--I--/,/--J--|--F--|--H--/' | head -n -1 | tail -n +2 | head -c 5000)
response_headers=$(echo "$block" | awk '/--F--/,/--H--|--K--|--Z--/' | head -n -1 | tail -n +2)

# Parse matched rules from H section
matched_rules_json="["
first=1
echo "$block" | awk '/--H--/,/--Z--/' | grep -oE '\[id "[0-9]+"\][^\[]*\[msg "[^"]*"\][^\[]*\[severity "[A-Z]+"\]' | while IFS= read -r match; do
    rid=$(echo "$match" | grep -oE 'id "[0-9]+"' | grep -oE '[0-9]+')
    msg=$(echo "$match" | grep -oE 'msg "[^"]+"' | sed 's/msg "//;s/"$//')
    sev=$(echo "$match" | grep -oE 'severity "[A-Z]+"' | sed 's/severity "//;s/"$//')

    [[ -z "$rid" ]] && continue
    [[ $first -eq 0 ]] && echo -n "," >> /tmp/mrules-$$
    first=0
    jq -nc --arg rid "$rid" --arg msg "$msg" --arg sev "$sev" \
        '{rule_id:$rid,severity:$sev,msg:$msg}' >> /tmp/mrules-$$
done

if [[ -f /tmp/mrules-$$ ]]; then
    matched_rules_json="[$(cat /tmp/mrules-$$ | paste -sd, -)]"
    rm -f /tmp/mrules-$$
fi

jq -nc \
    --arg event_id "$event_id" \
    --arg req_headers "$request_headers" \
    --arg req_body "$request_body" \
    --arg resp_headers "$response_headers" \
    --argjson all_matched_rules "$matched_rules_json" \
    '{ok:true, event_id:$event_id, request_headers:$req_headers, request_body:$req_body, response_headers:$resp_headers, all_matched_rules:$all_matched_rules}'
