#!/usr/bin/env bash
# Set up the Coraza-SPOA WAF sidecar's host-side prerequisites + default
# settings.json key.
#
# This is the one-time per-server install (idempotent — re-runs are no-ops
# beyond a chown / mkdir). It does NOT enable the WAF — coraza_waf.mode
# defaults to "off". Operators flip it on per-server via Server Settings ->
# Security in the WHP UI. Auto-enabling on every install would risk
# surprising customer-traffic blocks from any new server's first deploy.
#
# What this script does, idempotently:
#   1. ensure /var/log/coraza exists and is owned by UID 65532 (the
#      distroless coraza-spoa nonroot user)
#   2. ensure /docker/coraza exists for the runtime overrides bind-mount
#   3. seed coraza_waf.mode = "off" in /docker/whp/settings.json if missing
#   4. add the audit log to /etc/whp/ai-monitor.conf [log_sources] so
#      future WAF events are caught by the existing AI Monitor pipeline

set -euo pipefail

SETTINGS=/docker/whp/settings.json
AI_MONITOR_CONF=/etc/whp/ai-monitor.conf
HOST_AUDIT_DIR=/var/log/coraza
CORAZA_DIR=/docker/coraza

# ---- 1. host audit log dir (distroless UID 65532 writes here) ------------
mkdir -p "$HOST_AUDIT_DIR"
if [[ "$(stat -c %u "$HOST_AUDIT_DIR")" != "65532" ]]; then
    chown 65532:65532 "$HOST_AUDIT_DIR"
    echo "  ${HOST_AUDIT_DIR}: chown 65532:65532"
else
    echo "  ${HOST_AUDIT_DIR}: ownership OK"
fi

# ---- 2. runtime overrides dir --------------------------------------------
mkdir -p "$CORAZA_DIR"
echo "  ${CORAZA_DIR}: ready"

# ---- 3. seed coraza_waf.mode = "off" in settings.json --------------------
if [[ ! -f "$SETTINGS" ]]; then
    echo "ERROR: $SETTINGS missing — WHP not fully installed?" >&2
    exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
    echo "ERROR: jq required for settings.json mutation" >&2
    exit 1
fi

CURRENT_MODE=$(jq -r '.coraza_waf.mode // empty' "$SETTINGS")
if [[ -z "$CURRENT_MODE" ]]; then
    echo "  seeding coraza_waf.mode=off in $SETTINGS"
    TMP=$(mktemp)
    jq '.coraza_waf = (.coraza_waf // {}) | .coraza_waf.mode = "off" | .updated_at = (now | strftime("%Y-%m-%d %H:%M:%S"))' \
        "$SETTINGS" > "$TMP"
    mv "$TMP" "$SETTINGS"
    chmod 600 "$SETTINGS"
else
    echo "  coraza_waf.mode already set to '$CURRENT_MODE' — leaving alone"
fi

# ---- 4. add coraza audit log to AI Monitor sources -----------------------
# AI Monitor's config file is /etc/whp/ai-monitor.conf with INI-style
# [log_sources] section, key = path. Add our source there idempotently.
if [[ -f "$AI_MONITOR_CONF" ]]; then
    if grep -q "^coraza_audit\s*=" "$AI_MONITOR_CONF"; then
        echo "  ${AI_MONITOR_CONF}: coraza_audit already listed"
    else
        # Insert after the [log_sources] section header, or append a new
        # section if it doesn't exist. awk handles both cases.
        TMP=$(mktemp)
        awk '
            BEGIN { added = 0; in_log_sources = 0 }
            /^\[log_sources\]/ { in_log_sources = 1; print; next }
            /^\[/ && in_log_sources && !added {
                print "coraza_audit = /var/log/coraza/audit.log"
                added = 1
                in_log_sources = 0
            }
            { print }
            END {
                if (!added && !in_log_sources) {
                    print ""
                    print "[log_sources]"
                    print "coraza_audit = /var/log/coraza/audit.log"
                } else if (!added) {
                    print "coraza_audit = /var/log/coraza/audit.log"
                }
            }
        ' "$AI_MONITOR_CONF" > "$TMP"
        mv "$TMP" "$AI_MONITOR_CONF"
        echo "  ${AI_MONITOR_CONF}: added coraza_audit source"
    fi
else
    echo "  ${AI_MONITOR_CONF} missing — skipping AI Monitor wiring (it'll pick up after AI Monitor is installed)"
fi

echo
echo "setup-coraza-spoa.sh: OK"
echo "  WAF state    : disabled (coraza_waf.mode = $(jq -r '.coraza_waf.mode' "$SETTINGS"))"
echo "  Audit log    : $HOST_AUDIT_DIR/audit.log (UID 65532)"
echo "  To enable    : Server Settings -> Security -> Web Application Firewall"
echo "  Or via CLI   : jq '.coraza_waf.mode = \"detect_only\"' $SETTINGS > /tmp/s && mv /tmp/s $SETTINGS && /root/whp/scripts/apply-coraza-waf-mode.sh"
