#!/bin/bash

#
# Anti-virus Scanner !
# 
function die()
{
   RETCODE=${1}
   MSG=${2}

   echo "${MSG}"
   exit ${RETCODE}
}

function log()
{
   logger -t "eole-antivirus" "$@"
}

function showHelp()
{
   echo "$(basename ${0}): Lancer une analyse anti-virus"
   echo "  -e : mode EOLE Analayse les répertoires configurés dans l'onglet Clamav de Gen_Config"
   echo "  -s : mode Samba analyse les partages samba"
   echo "  -d : mode manuel analyse le répertoire passé en paramètre"
   echo
   echo "Scan EOLE : $(basename ${0}) -e"
   echo "Scan Samba : $(basename ${0}) -s"
   echo "Scan Manuel : $(basename ${0}) -d /tmp -d /etc"
   echo "Scan mixte : $(basename ${0}) -e -s -d /tmp -d /etc -d /usr/share"
   echo "Attention les répertoires spécifiés avec -d doivent être accècibles par le démon clamd (y compris au niveau apparmor)"
   echo ""
   echo "Fichier de logs disponible ici : /var/log/rsyslog/local/eole-antivirus"
   die 3 ""
}

MODE="DEFAULT"
TARGETS=""

while getopts ":esfhd:" opt; do
  case ${opt} in
    e) MODE="eole"  ;;
    s) MODE="samba" ;;
    d) 
       MODE="custom" 
       TARGETS="${TARGETS} ${OPTARG}"
    ;;
    h) showHelp ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done


if [[ ${MODE} == "samba" ]] || [[ ${MODE} == "full" ]]
then
   # Manage Samba shares scan !!
   if [[ $(CreoleGet activer_ad_share_scan non) == "oui" ]]
   then
      if [[ $(CreoleGet activer_ad_home_share non)  == "oui" ]]  
      then
         TARGETS="${TARGETS} $(CreoleGet ad_home_share_path "")"
      fi
      if [[ $(CreoleGet ad_additional_share non)  == "oui" ]]  
      then
         TARGETS="${TARGETS} $(CreoleGet ad_additional_share_path "")"
      fi
   fi
elif [[ ${MODE} == "eole" ]] || [[ ${MODE} == "full" ]]
then
   # Manage directories from anti-virus familly
   TARGETS="${TARGETS} $(CreoleGet clam_scan_dir "")"
elif [[ ${MODE} == "custom" ]]
then
   # The user can set Custom Targets
   TARGETS="${TARGETS}"
else
   # Unsupported modes
   showHelp
fi
   
ENABLED=$(CreoleGet activer_scandir non)
if [[ ${ENABLED} == "non" ]] 
then 
   [[ -z ${TARGETS} ]] && die 0 "No directory configured for automatic scan"
   # Manage Active Directory homes
fi

SCAN="clamdscan"
OPTS=""

if [[ ${TARGETS} != "" ]]
then
   log '============ SCAN REPORT ============'
   ${SCAN} ${OPTS} ${TARGETS} | log
   log '====================================='
fi
