#!/usr/bin/env bash
# Coraza rule manager — create SQLite tables in security.db that back the
# WHP admin UI for runtime CRS rule tuning.
#
# Idempotent: CREATE TABLE IF NOT EXISTS for everything. Safe to re-run.

set -euo pipefail

SECURITY_DB="/docker/whp/sql/security.db"

if [[ ! -f "$SECURITY_DB" ]]; then
    echo "Security DB not found at $SECURITY_DB — skipping (server hasn't run log monitor yet)"
    exit 0
fi

# The sqlite3 CLI is not part of the baseline on older WHP installs; older
# setup.sh runs predate its inclusion in the package list. Install it on demand
# so this script runs cleanly regardless of install vintage. dnf is a no-op
# when the package is already present.
if ! command -v sqlite3 >/dev/null 2>&1; then
    echo "sqlite3 CLI missing — installing"
    dnf install -y sqlite >/dev/null
fi

sqlite3 "$SECURITY_DB" <<'SQL'
CREATE TABLE IF NOT EXISTS coraza_rule_overrides (
    rule_id      INTEGER PRIMARY KEY,
    state        TEXT NOT NULL CHECK(state IN ('enforce','detect','off')),
    note         TEXT,
    updated_at   INTEGER NOT NULL,
    updated_by   TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS coraza_rule_host_exceptions (
    rule_id      INTEGER NOT NULL,
    hostname     TEXT NOT NULL,
    note         TEXT,
    updated_at   INTEGER NOT NULL,
    updated_by   TEXT NOT NULL,
    PRIMARY KEY (rule_id, hostname)
);

CREATE TABLE IF NOT EXISTS coraza_rule_audit_log (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    ts           INTEGER NOT NULL,
    actor        TEXT NOT NULL,
    rule_id      INTEGER NOT NULL,
    action       TEXT NOT NULL,
    payload      TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_coraza_audit_ts ON coraza_rule_audit_log(ts DESC);

CREATE TABLE IF NOT EXISTS coraza_rule_hits (
    rule_id      INTEGER NOT NULL,
    window       TEXT NOT NULL,
    hits         INTEGER NOT NULL,
    top_hosts    TEXT NOT NULL,
    top_uris     TEXT NOT NULL,
    computed_at  INTEGER NOT NULL,
    PRIMARY KEY (rule_id, window)
);
SQL

echo "setup-coraza-rule-manager.sh: OK"
