#!/usr/bin/env bash
# onx-clamav-status — ClamAV kurulum/daemon/imza durumu (JSON)
# NOT: common.sh `set -euo pipefail` aktif. sigtool|awk gibi ERKEN-ÇIKIŞLI pipe'lar
# (awk 'exit', head) üreticiye SIGPIPE gönderir → pipefail bunu "fail" sayar →
# set -e scripti abort eder (boş çıktı). Bu yüzden her birine `|| true` eklendi.
source "$(dirname "$0")/_lib/common.sh"
require_root
require_cmd jq

INSTALLED=false; RUNNING=false; VERSION=""; DBVER=""; DBUPD=""; OFFICIAL=0
DBDIR="/var/lib/clamav"

if command -v clamdscan &>/dev/null || command -v clamscan &>/dev/null; then
    INSTALLED=true
    VERSION="$( { clamdscan --version 2>/dev/null || clamscan --version 2>/dev/null; } | head -n1 || true)"
fi
if systemctl is-active --quiet clamav-daemon 2>/dev/null || systemctl is-active --quiet clamd@scan 2>/dev/null; then
    RUNNING=true
fi

# daily DB sürüm + son güncelleme zamanı
if [[ -f "$DBDIR/daily.cld" || -f "$DBDIR/daily.cvd" ]]; then
    DAILY="$DBDIR/daily.cld"; [[ -f "$DBDIR/daily.cvd" ]] && DAILY="$DBDIR/daily.cvd"
    DBVER="$(sigtool --info "$DAILY" 2>/dev/null | awk -F': *' '/^Version/{print $2; exit}' || true)"
    DBUPD="$(date -u -r "$DAILY" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || true)"
fi

# Resmi imza sayısı: main+daily HEADER'larından topla (hızlı; list-sigs 3.6M satır taramaz)
for f in "$DBDIR/main.cvd" "$DBDIR/main.cld" "$DBDIR/daily.cvd" "$DBDIR/daily.cld"; do
    [[ -f "$f" ]] || continue
    n="$(sigtool --info "$f" 2>/dev/null | awk -F': *' '/^Signatures/{print $2; exit}' || true)"
    n="$(printf '%s' "$n" | tr -dc '0-9')"
    OFFICIAL=$((OFFICIAL + ${n:-0}))
done

# Feed durumları: SaneSecurity + LMD dosyalarını say (değerler temiz integer'a sanitize)
SANE_CNT="$(find "$DBDIR" -maxdepth 1 -name 'sanesecurity.*' 2>/dev/null | wc -l | tr -dc '0-9')"; SANE_CNT="${SANE_CNT:-0}"
LMD_CNT="$(find "$DBDIR" -maxdepth 1 -name 'lmd.*' 2>/dev/null | wc -l | tr -dc '0-9')"; LMD_CNT="${LMD_CNT:-0}"
FEEDS_JSON="$(jq -n --argjson sane "$SANE_CNT" --argjson lmd "$LMD_CNT" \
    '[{name:"sanesecurity",sigs:$sane,updated_at:null},{name:"lmd",sigs:$lmd,updated_at:null}]')"

json_ok "$(jq -n \
    --argjson installed "$INSTALLED" --argjson running "$RUNNING" \
    --arg version "$VERSION" --arg db_version "$DBVER" --arg db_last_updated "$DBUPD" \
    --argjson official_sigs "${OFFICIAL:-0}" --argjson feeds "$FEEDS_JSON" \
    '{installed:$installed,running:$running,version:$version,db_version:$db_version,db_last_updated:(if $db_last_updated=="" then null else $db_last_updated end),official_sigs:$official_sigs,feeds:$feeds}')"
