#! /bin/bash

set -e

export LANG=C
export LC_CTYPE=C

# Script to automatically check whether the installed clamav databases
# can be used to correctly find clamav-testfiles and eicar.com

# Written by Marc Haber <mh+debian-packages@zugschlus.de>

[ "$CLAMSCAN" ] || CLAMSCAN="$(which clamscan)"

umask 002
CLAMSCAN_OPTS="${CLAMSCAN_OPTS:-}"

OUTPUTFILE=$(mktemp -t clamscanoutput.XXXXXX) || { echo "$0: Cannot create temporary file" >&2; exit 1;  }
trap " [ -f \"$OUTPUTFILE\" ] && /bin/rm -f -- \"$OUTPUTFILE\"" 0 1 2 3 13 15

if ! [ -x "$CLAMSCAN" ]; then
	echo >&2 "ERR: no clamscan in path. Aborting."
	exit 1
fi

if ! dpkg --list clamav-testfiles >/dev/null 2>/dev/null; then
	echo >&2 "ERR: no clamav-testfiles installed. Aborting."
	exit 1
fi

CLAMAVVER="$(dpkg --list libclamav1 | sed -n '/^ii/{s/^ii[[:space:]]\+[^[:space:]]\+[[:space:]]\+\([^[:space:]]\+\).*/\1/;p;q;}')"

if [ -z "$REFNUMBADFILES" ]; then
    if dpkg --compare-versions "$CLAMAVVER" ">=" "0.90~rc3"; then
        REFNUMBADFILES="6"
    else
        REFNUMBADFILES="5"
    fi
fi
    
clamavtest()
{
    local TESTDIR
    local REFNUMBADFILES
    local FOUNDSTRING
    local EXPLSTRING
    local RET
    local NUMBADFILES
    TESTDIR="$1"
    REFNUMBADFILES="$2"
    FOUNDSTRING="$3"
    EXPLSTRING="$4"
	
    echo "$CLAMSCAN $CLAMSCAN_OPTS --recursive $TESTDIR"
    RET=0
    $CLAMSCAN $CLAMSCAN_OPTS --recursive $TESTDIR > $OUTPUTFILE 2>&1 || RET=$?
    cat $OUTPUTFILE
    if [ $RET -ne 1 ] ; then
        echo >&2 "An error ($RET) occured while scanning $EXPLSTRING."
        exit 2
    fi
    NUMBADFILES=$(< $OUTPUTFILE grep "$FOUNDSTRING" | wc -l)
    if [ $NUMBADFILES -ne $REFNUMBADFILES ]; then
        echo >&2 "Wrong number ($NUMBADFILES/$REFNUMBADFILES) of 'infected' files detected while scanning clamav test files"
        exit 2
    fi
}


[ "$CLAMAVTESTFILES" ] || CLAMAVTESTFILES="/usr/share/clamav-testfiles"
clamavtest "$CLAMAVTESTFILES" "$REFNUMBADFILES" "ClamAV-Test-File FOUND" "clamav test files"

[ "$EICAR" ] || EICAR="/var/lib/clamav-getfiles/eicar.com"
if [ -f "$EICAR" ]; then
    clamavtest "$EICAR" "1" "Eicar-Test-Signature FOUND" "EICAR Anti-Virus Test-File"
else
    echo "No test scan against eicar.com done, file not present on system."
    echo "You might want to point the EICAR environment variable to the file."
fi
