#!/usr/bin/env bash
set -Eeuo pipefail

PATH="/usr/sbin:/usr/bin:/sbin:/bin"
LOG_DIR="/var/log/security/malware"
LOCK_FILE="/var/lock/security_malware_scan.lock"
RETENTION_DAYS="120"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
LOG_FILE="${LOG_DIR}/malware-scan-${TIMESTAMP}.log"

if [[ "${EUID}" -ne 0 ]]; then
  echo "ERROR: This script must run as root." >&2
  exit 2
fi

for cmd in flock tee find date mktemp grep wc awk cat rm head sed; do
  if ! command -v "${cmd}" >/dev/null 2>&1; then
    echo "ERROR: Required command not found: ${cmd}" >&2
    exit 2
  fi
done

mkdir -p "${LOG_DIR}" "$(dirname "${LOCK_FILE}")"
touch "${LOG_FILE}"

exec 9>"${LOCK_FILE}"
if ! flock -n 9; then
  echo "INFO: Malware scan already running; exiting."
  exit 0
fi

runCount=0
overallRc=0

logLine() {
  echo "$1" | tee -a "${LOG_FILE}"
}

logLine "==== Weekly malware scan started: $(date -Is) ===="
logLine "Log file: ${LOG_FILE}"

# Prune old logs to control disk usage.
find "${LOG_DIR}" -maxdepth 1 -type f -name 'malware-scan-*.log' -mtime +"${RETENTION_DAYS}" -delete || true

if command -v rkhunter >/dev/null 2>&1; then
  runCount=$((runCount + 1))
  rkhTmp="$(mktemp)"
  logLine "rkhunter: running"

  if rkhunter --check --skip-keypress --report-warnings-only >"${rkhTmp}" 2>&1; then
    rkhRc=0
  else
    rkhRc=$?
    overallRc=1
  fi

  cat "${rkhTmp}" >> "${LOG_FILE}"
  rkhWarnings="$(grep -Eic 'warning:' "${rkhTmp}" || true)"
  logLine "rkhunter: rc=${rkhRc} warnings=${rkhWarnings}"
  if [[ "${rkhWarnings}" -gt 0 ]]; then
    logLine "rkhunter: first warning lines"
    grep -Ei 'warning:' "${rkhTmp}" | head -n 5 | sed 's/^/  /' | tee -a "${LOG_FILE}"
  fi
  rm -f "${rkhTmp}"
else
  logLine "rkhunter: not installed (skipped)"
fi

if command -v chkrootkit >/dev/null 2>&1; then
  runCount=$((runCount + 1))
  chkTmp="$(mktemp)"
  logLine "chkrootkit: running"

  if chkrootkit >"${chkTmp}" 2>&1; then
    chkRc=0
  else
    chkRc=$?
    overallRc=1
  fi

  cat "${chkTmp}" >> "${LOG_FILE}"
  chkAlerts="$(grep -Eic 'INFECTED|Vulnerable' "${chkTmp}" || true)"
  logLine "chkrootkit: rc=${chkRc} alerts=${chkAlerts}"
  if [[ "${chkAlerts}" -gt 0 ]]; then
    logLine "chkrootkit: first alert lines"
    grep -Ei 'INFECTED|Vulnerable' "${chkTmp}" | head -n 5 | sed 's/^/  /' | tee -a "${LOG_FILE}"
  fi
  rm -f "${chkTmp}"
else
  logLine "chkrootkit: not installed (skipped)"
fi

if [[ "${runCount}" -eq 0 ]]; then
  logLine "WARNING: No malware scanners are installed (rkhunter/chkrootkit)."
fi

logLine "==== Weekly malware scan finished: $(date -Is) (exit ${overallRc}) ===="

exit "${overallRc}"
