#!/bin/sh

TRENDDIR="/etc/iscan"
cd $TRENDDIR
mkdir -p tmp old
cd tmp



DATE=`date +%Y%m%d`


wget -q -O pattern.htm ftp://pattern.download.antivirus.com/products/pattern/
if [ "$?" != "0" ]; then
	echo "Something's wrong - wget exited non-zero"
	exit
fi

SITE=`egrep "lpt.*zip" pattern.htm |sed -e 's/^.*HREF="//ig' -e 's/".*$//g' |tail -1`

FILE=`basename $SITE`

if [ "$FILE" = "" ]; then
	echo "Something's wrong - couldn't find primary download site, exiting"
	exit
fi

#looks like it's up!
if [ -f "$TRENDDIR/$FILE" ]; then
        echo "Latest file is $FILE and it has already been got, exiting..."
	exit
fi
wget -qc ftp://pattern.download.antivirus.com/products/pattern/$FILE
if [ "$?" != "0" ]; then
	 echo "Download of new zip file failed - exiting"
	 rm -f $FILE
	 exit
fi
unzip -t $FILE >/dev/null 2>&1
if [ "$?" != "0" ]; then
	 echo "Downloaded zip file - but it's corrupt - exiting..."
	 rm -f $FILE
	 exit
else
	echo "Unpacked ZIP file $FILE - now test..."
fi
#Now unzip zip file into tmp dir for test run
mkdir -p scantmp
cd scantmp
#Grab copies of live lpt* files as this zip may not have everything
for i in $TRENDDIR/lpt\$*
do
    cp -f $i .
done

unzip -oL ../$FILE >/dev/null 2>&1
#
#Now run vscan against test virus to ensure it's working

#Create test virus file
echo 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' > eicar.com
DD=`/etc/iscan/vscan -p$PWD -za -u eicar.com`
rm -f eicar.com

if [ "`echo $DD|grep '*** Found virus'`" = '' ]; then
	echo "Didn't detect EICAR test virus - Email admin - exiting"
	(cat<<EOF
From: Virus Scanner Downloader <root>
To: virus-reports
Subject: Bad ZIP file of Trends DAT files

$FILE contains DAT files that do not recognise the EICAR.COM test virus. As
such the DAT files will NOT go live.

See files in $TRENDDIR/tmp/scantmp for details

EOF
)|/usr/sbin/sendmail -oi -t
	exit
fi

echo "Passed EICAR test - move new DAT files from $FILE live"


#sweet. Copy old dat files away - don't rename as new zip file
#may not contain all the dat files!!!!
for i in $TRENDDIR/lpt\$*
do
    if [ "`ls $TRENDDIR/old/`basename $i`* 2>/dev/null`" = "" ]; then
    	cp -f $i $TRENDDIR/old/`basename $i`-$DATE
    fi
done

#Joy - everything is sweeeeet! Move files live
chmod 755 * ../$FILE
mv -f * ../$FILE $TRENDDIR/
chmod 755 $TRENDDIR/*
cd ..
rmdir scantmp
#Update version file for Email virus 
/var/qmail/bin/qmail-scanner-queue.pl -z
	
#Clean up old files
find $TRENDDIR  -mtime +14 \( -name '*.zip' -o  -name 'lpt*-*' \) -exec rm -f {} \;
