#!/usr/bin/env bash
# onx-clamav-onaccess — gerçek-zamanlı (clamonacc) korumayı aç/kapat.
# Dağıtım-bağımsız: clamd config yolu + servis + clamonacc binary otomatik tespit edilir.
#   RHEL/AlmaLinux: /etc/clamd.d/scan.conf + clamd@scan
#   Debian/Ubuntu : /etc/clamav/clamd.conf + clamav-daemon
source "$(dirname "$0")/_lib/common.sh"
require_root
onx_json_input
ENABLE="$(onx_json_field enable '0')"
UNIT="onoxsoft-clamonacc.service"
UNITFILE="/etc/systemd/system/${UNIT}"

# clamd config yolunu tespit et
CLAMD_CONF=""
for c in /etc/clamd.d/scan.conf /etc/clamav/clamd.conf; do
    [[ -f "$c" ]] && CLAMD_CONF="$c" && break
done
[[ -n "$CLAMD_CONF" ]] || onx_die 2 "clamd config bulunamadı (clamav kurulu mu?)"

# clamd servis adı + clamonacc binary
CLAMD_SVC="clamd@scan"
systemctl list-unit-files 2>/dev/null | grep -q '^clamav-daemon\.service' && CLAMD_SVC="clamav-daemon"
CLAMONACC="$(command -v clamonacc 2>/dev/null || echo /usr/sbin/clamonacc)"

if [[ "$ENABLE" == "1" || "$ENABLE" == "true" ]]; then
    # On-access izlenen yol clamd config'e eklenir (idempotent). Prevention=no → engelleme
    # yapma, sadece tara+karantinaya taşı (sitleri kilitleme riski yok).
    grep -q '^OnAccessIncludePath /home/users' "$CLAMD_CONF" 2>/dev/null || \
        printf 'OnAccessIncludePath /home/users\nOnAccessPrevention no\nOnAccessExtraScanning yes\n' >> "$CLAMD_CONF"
    # OnAccessExclude* ŞART: clamonacc (root) + clamd kullanıcısı kendi dosya erişimlerini
    # tarayıp sonsuz döngüye girmesin. Eksikse clamonacc başlangıçta "at least one of
    # OnAccessExclude... must be specified" (INVALIDARGUMENT, exit 2) ile başlamaz.
    CLAMD_USER="$(getent passwd clamscan >/dev/null 2>&1 && echo clamscan || echo clamav)"
    grep -q '^OnAccessExclude' "$CLAMD_CONF" 2>/dev/null || \
        printf 'OnAccessExcludeUname %s\nOnAccessExcludeRootUID yes\n' "$CLAMD_USER" >> "$CLAMD_CONF"
    cat >"$UNITFILE" <<EOF
[Unit]
Description=OnoxSoft ClamAV On-Access Scanner
After=${CLAMD_SVC}.service
Requires=${CLAMD_SVC}.service
[Service]
ExecStart=${CLAMONACC} -F --fdpass --move=/var/lib/onoxsoft/quarantine
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl restart "$CLAMD_SVC" &>/dev/null || true
    systemctl enable --now "$UNIT" &>/dev/null || true
    RUNNING=true
else
    systemctl disable --now "$UNIT" &>/dev/null || true
    RUNNING=false
fi
onx_json_out ok true running "$RUNNING"
