#!/bin/bash
set -e
echo "======================================"
echo " MALDET INSTALL / ONE-TIME SCAN"
echo "======================================"
LOGFILE="/root/maldet_install.log"
exec > >(tee -a "$LOGFILE") 2>&1

echo "[INFO] Started at: $(date)"

# Detect package manager
if command -v dnf >/dev/null 2>&1; then
    PKG="dnf"
elif command -v yum >/dev/null 2>&1; then
    PKG="yum"
else
    echo "[ERROR] No supported package manager found"
    exit 1
fi

echo "[INFO] Installing dependencies"
$PKG install -y wget tar curl

echo "[INFO] Moving to source directory"
if ! cd /usr/local/src; then
    echo "[ERROR] Cannot access /usr/local/src"
    exit 1
fi

echo "[INFO] Cleaning old Maldet files"
rm -rf maldetect-*/
rm -f maldetect-current.tar.gz

echo "[INFO] Downloading latest Maldet"
wget -q http://www.rfxn.com/downloads/maldetect-current.tar.gz
if [ ! -f maldetect-current.tar.gz ]; then
    echo "[ERROR] Download failed"
    exit 1
fi

echo "[INFO] Extracting package"
tar -xzf maldetect-current.tar.gz

echo "[INFO] Entering extracted directory"
MALDET_DIR=$(find /usr/local/src -maxdepth 1 -type d -name 'maldetect-*' | head -1)
if [ -z "$MALDET_DIR" ]; then
    echo "[ERROR] Maldet directory not found"
    exit 1
fi

if ! cd "$MALDET_DIR"; then
    echo "[ERROR] Cannot enter $MALDET_DIR"
    exit 1
fi

echo "[INFO] Installing / Updating Maldet"
./install.sh

echo "[INFO] Updating signatures"
maldet -u

echo "[INFO] Installed version:"
maldet --version

echo "[INFO] Starting one-time background scan for /home modified in last 2 days"
maldet -b -r /home 2

echo "[INFO] Cleaning installer files"
cd /usr/local/src
rm -rf maldetect-*/
rm -f maldetect-current.tar.gz

echo "======================================"
echo " MALDET INSTALL & SCAN COMPLETED"
echo "======================================"
echo "[INFO] Completed at: $(date)"
echo "[INFO] Log file: $LOGFILE"
