#!/usr/bin/env bash
#
# onx-modsec-vendor-list — Kurulu ModSecurity vendor ruleset'leri listele.
#
# Common locations:
#   /etc/httpd/modsecurity.d/owasp-crs    (OWASP CRS)
#   /etc/httpd/modsecurity.d/comodo       (Comodo WAF)
#   /etc/httpd/modsecurity.d/atomicorp    (Atomicorp)
#
# Output: {"vendors":[{slug, name, version, rules_count, install_path}]}

set -euo pipefail

readonly MODSEC_BASE="/etc/httpd/modsecurity.d"

vendors_json="["
first=1

# Check each known vendor path
for entry in \
    "owasp_crs:OWASP Core Rule Set:owasp-crs" \
    "comodo_cwaf:Comodo WAF:comodo" \
    "atomicorp:Atomicorp Free WAF:atomicorp"; do
    IFS=: read -r slug name dir <<<"$entry"
    path="$MODSEC_BASE/$dir"

    [[ ! -d "$path" ]] && continue

    # Find version from setup file or VERSION file
    version=""
    if [[ -f "$path/crs-setup.conf.example" ]]; then
        version=$(grep -oE '#[[:space:]]+ModSecurity Core Rule Set ver\.\s*[0-9.]+' "$path/crs-setup.conf.example" 2>/dev/null | head -1 | grep -oE '[0-9.]+' || true)
    fi
    [[ -z "$version" && -f "$path/VERSION" ]] && version=$(cat "$path/VERSION" 2>/dev/null | head -1 || true)
    [[ -z "$version" ]] && version="unknown"

    # Count rules
    rules_count=0
    if [[ -d "$path/rules" ]]; then
        rules_count=$(find "$path/rules" -name '*.conf' -exec grep -hcE '^[[:space:]]*SecRule' {} \; 2>/dev/null | paste -sd+ - | bc 2>/dev/null || echo 0)
    elif [[ -d "$path" ]]; then
        rules_count=$(find "$path" -maxdepth 2 -name '*.conf' -exec grep -hcE '^[[:space:]]*SecRule' {} \; 2>/dev/null | paste -sd+ - | bc 2>/dev/null || echo 0)
    fi

    [[ $first -eq 0 ]] && vendors_json+=","
    first=0
    vendors_json+="$(jq -nc \
        --arg slug "$slug" --arg name "$name" --arg version "$version" \
        --argjson rules_count "$rules_count" --arg path "$path" \
        --argjson is_official "$([[ "$slug" == "owasp_crs" ]] && echo true || echo false)" \
        '{slug:$slug, name:$name, version:$version, rules_count:$rules_count, install_path:$path, is_official:$is_official}')"
done

vendors_json+="]"

jq -nc --argjson vendors "$vendors_json" '{ok:true, vendors:$vendors}'
