#!/bin/bash
#
# Copyright Security Onion Solutions LLC and/or licensed to Security Onion Solutions LLC under one
# or more contributor license agreements. Licensed under the Elastic License 2.0 as shown at
# https://securityonion.net/license; you may not use this file except in compliance with the
# Elastic License 2.0.

# Query Suricata for ruleset stats and reload time, write to JSON file for Telegraf to consume

OUTFILE="/opt/so/log/suricata/rulestats.json"
SURICATASC="docker exec so-suricata /opt/suricata/bin/suricatasc"
SOCKET="/var/run/suricata/suricata-command.socket"

query() {
    timeout 10 $SURICATASC -c "$1" "$SOCKET" 2>/dev/null
}

STATS=$(query "ruleset-stats")
RELOAD=$(query "ruleset-reload-time")
[ -z "$RELOAD" ] && RELOAD='{}'

# Outputs valid JSON on success, empty on failure
OUTPUT=$(jq -n \
    --argjson stats "$STATS" \
    --argjson reload "$RELOAD" \
    'if $stats.return == "OK" and ($stats.message[0].rules_loaded | type) == "number" and ($stats.message[0].rules_failed | type) == "number" then
        {
            rules_loaded: $stats.message[0].rules_loaded,
            rules_failed: $stats.message[0].rules_failed,
            last_reload: ($reload.message[0].last_reload // ""),
            return: "OK"
        }
    else empty end' 2>/dev/null)

if [ -n "$OUTPUT" ]; then
    echo "$OUTPUT" > "$OUTFILE"
else
    echo '{"return":"FAIL"}' > "$OUTFILE"
fi
