#!/bin/bash
# ***************************************************************************
# * SCANFILES Script                                  Ben Makkink 16/10/2024*
# * Met het ClamAv programma 'clamscan' wordt een scan van gespecificeerde  *
# * mappen uitgevoerd. Als er malware gevonden wordt, word er een e-mail    *
# * naar Admin gestuurd.                                                    *
# * Dit script wordt uitgevoerd doormiddel van een cron.daily               *
# * Edit bestand /var/clamav/scandirs met lijst van te scannen dirs         *
# ***************************************************************************

SCANDIRS="/var/clamav/scandirs";
QUARANTINEDIR="/var/clamav/quarantine";
LOGFILE="/var/log/clamav/scanfiles.log";
NEWPATHS="/var/clamav/newpaths";
RESTOREPATHS="/var/clamav/restorepaths";
EMAIL_MSG="Resultaat dagelijkse ClamAV scan:";
EMAIL_FROM="thuisserver@makkink.eu";
EMAIL_TO="ben@makkink.eu";

# Lees SCANDIRS met lijst te scannnen dirs voor DIRTOSCAN
DIRTOSCAN=$(tail -1 ${SCANDIRS});

#Disable freshclam.service
echo "Disable clamav-freshclam.service"
systemctl stop clamav-freshclam.service;

# Update ClamAV database
echo "Looking for ClamAV database updates...";
freshclam --quiet;

# Verwijder oude log
if [ -f "${LOGFILE}" ]; then
 rm "${LOGFILE}";
fi

MALWARE=0;
for S in ${DIRTOSCAN}; do
  # total size if we use something like /home/*/public_html for scanning
  DIRSIZE=$(du -shc "$S" 2>/dev/null| cut -f1 | tail -1)
  echo -e "Starting a daily scan of "$S" directory.\nAmount of data to be scanned is "${DIRSIZE}".";
  nice -n19 clamscan -ri --exclude=".img" --exclude=".iso" "$S" >>"${LOGFILE}"
  # get the value of "Infected lines"
  MALWARE=$(($MALWARE+$(tail "${LOGFILE}"|grep Infected|cut -d" " -f3)));
done

# if the value is not equal to zero, send an email with the log details included
if [ "${MALWARE}" -ne "0" ]; then
	#compose content e-mail message
	body=$'\n'${EMAIL_MSG}$'\n'"==========================================="$'\n';
	body+="$(cat "${LOGFILE}")";
	body+=$'\n'$'\n'"De bestanden met Malware zijn naar '/var/clamav/quarantine' verplaatst";
	body+=$'\n'$'\n'"SSH naar 'Utils > ClamScan' om dit af te handelen";
	
	#Send e-mail message
	echo "$body"|mail -s "ClamAV: Malware gevonden" -r "${EMAIL_FROM}" "${EMAIL_TO}";

	# Move files with malware to quarantine
	# get newpaths of infected files from logfile"
	echo "$(grep FOUND "${LOGFILE}"|cut -d: -f1)" > "${NEWPATHS}";
        # Store paths for restore
	echo "$(grep FOUND "${LOGFILE}"|cut -d: -f1)" >> "${RESTOREPATHS}";
	# read newpaths file and move infected files to quarantine
	while IFS= read -r file;
	do
	  mv "$file" "${QUARANTINEDIR}";
	done < "${NEWPATHS}"
fi

#Re-enable clamav-freshclam.service
echo "Enable clamav-freshclam.service back again"
systemctl start clamav-freshclam.service;

echo "The script has finished.";
exit 0;
