#!/bin/sh

# Trend Autoupdate Script.
# V0.1 Dan Bird. dbird@sghms.ac.uk
# 12/08/2003

# Make it work on new POSIX systems
export _POSIX2_VERSION=199209

PackageDir=$1
export PackageDir
shift

OPRINI=opr.ini.$$
export OPRINI

# source of IScan dat files
FTPSERV="ftp://ftp.antivirus.com/products/pattern/"

# Get the info on new version...
echo "Checking for latest DAT version..."
wget -q -O /tmp/$OPRINI $FTPSERV/opr.ini
#NEWVER=`grep PatternVersion /tmp/opr.ini.$$ | sed s/^PatternVersion=//g | cut -c 1-3`
NEWVER=`grep PatternVersionNPF /tmp/opr.ini.$$ | sed s/^PatternVersionNPF=//g | cut -c 3-5`

# What's out current version?
# For 2006 onwards CURRENTVER=`ls $PackageDir/* | grep lpt | tail -1 |  cut -d. -f 2`
CURRENTVER=`ls -rt $PackageDir/* | grep lpt | tail -1 |  cut -d. -f 2`

if [ "$CURRENTVER" = "" ]
then
        CURRENTVER=0
fi
echo "Current version is : $CURRENTVER, new version is : $NEWVER"

fail () {
        trap EXIT
        echo "Test run failed -- removing bad Trend data files"
        echo "$OUT"
        rm -rf $PackageDir/lpt*$NEWVER*
	logger -p mail.warn -t trend-autoupdate Trend: update failed
        exit 1
}

# If our current one is older, download the new one!!!
# For 2006 onwards if [ $CURRENTVER -lt $NEWVER ]
if [ $CURRENTVER -ne $NEWVER ]
then
        echo "Getting new DAT version : $NEWVER"
        wget -q -P /tmp  $FTPSERV/lpt$NEWVER.zip
        printf "Testing file for corruption...."

        DATCHECK=`unzip -o -t /tmp/lpt$NEWVER.zip | grep "No errors"`

        if [ "$DATCHECK" != "" ]
        then
                echo "OK"
                mv /tmp/lpt$NEWVER.zip /etc/iscan
                printf "installing...."
                cd $PackageDir
                unzip -q -o lpt$NEWVER.zip
                echo "DONE"
        else
                echo "BAD ARCHIVE"
        fi


        CMD="$PackageDir/vscan -v 2>&1"
        OUT=`$CMD`
        case "$OUT" in
                *"read pattern failed"* | \
                *"invalid pattern file"* | \
                *"pattern file not found"* | \
                *"incorrect pattern format"* | \
                *"read error"* | \
                *"out of memory"* )
        fail
        ;;
        esac
        trap EXIT
	logger -p mail.info -t trend-autoupdate Trend: DAT files updated from $CURRENTVER to $NEWVER
else
        echo "DAT files are upto date"
	logger -p mail.info -t trend-autoupdate Trend: DAT files are up to date
fi
rm -f /tmp/lpt*.zip /tmp/$OPRINI $PackageDir/*.zip
