#!/bin/sh -e
#
# Update the McAfee data files.
#
# $Cambridge: hermes/build/bin/uvscan-update,v 1.17 2003/04/11 18:47:00 fanf2 Exp $

# This is the directory where the uvscan binary is (NOT a symlink to
# the binary), which is where it looks for its dat files. You may run
# uvscan via a symlink to this place (e.g. from /usr/local/bin/uvscan)
# and it will still look for the dat files here. If uvscan's library
# dependencies can be found in a standard place (e.g. /usr/local/lib)
# then you don't need a wrapper script to set LD_LIBRARY_PATH before
# running it.
#
# The dat files are installed in a subdirectory named according to
# their version number, with symlinks from this directory into the
# subdirectory. The links are updated without locking on the
# assumption that this is sufficiently unlikely to cause a problem.
#
echo
echo "Mcafee uvscan update script"
echo
/bin/date
echo
LIBDIR=/usr/local/uvscan

FTPDIR=ftp://ftp.mcafee.com/pub/datfiles/english

# ensure the path is plausible
PATH=$LIBDIR:/usr/local/bin:/usr/bin:/bin

# version number pattern
MATCH=[0-9][0-9][0-9][0-9]

# work out latest dat version
SED="/^DATVersion=\($MATCH\).$/!d;s//\1/;q"
VERSION=$(wget --passive-ftp -q -O- $FTPDIR/update.ini | sed -e "$SED")

DATDIR=$LIBDIR/$VERSION
FILE=dat-$VERSION.tar

badversion () {
    echo Failed to get McAfee datfile update from "$FTPDIR"
    echo FTP version number "\"$VERSION\"" "$@"
    exit 1
}

# check the format of the version number
case $VERSION in
$MATCH)     : ok
    ;;
*)  badversion does not match "$MATCH"
    ;;
esac

# already got it?
if [ -d $DATDIR ]
then
    # keep cron quiet by default
    case $1 in
    -v)     echo Already have "$VERSION"
    esac
    exit
fi

# work out installed dat version
cd $LIBDIR
if ls -d $MATCH >/dev/null 2>&1
then
    INSTALLED=$(ls -d $MATCH | tail -1)
else
    # no installed version so get whatever is available
    INSTALLED=0000
fi

# check new version is actually newer
if [ $VERSION -lt $INSTALLED ]
then
    badversion older than installed "$INSTALLED"
fi

echo Installed dat file is "$INSTALLED"
echo Latest dat file is "$VERSION"

# now we are verbose
run() {
    echo ">" "$@"
    "$@"
}

# fetch and extract dat files
run mkdir $DATDIR
run cd $DATDIR
run wget --passive-ftp --progress=dot:mega $FTPDIR/$FILE
run tar xvf $FILE

# verify the contents
fail () {
    echo "$OUT"
    echo Test run failed -- removing bad McAfee data files
    run rm -rf $DATDIR
    exit 1
}
trap fail EXIT
CMD="uvscan --dat $DATDIR --version 2>&1"
echo '> OUT=$('$CMD')'
OUT=$($CMD)
case "$OUT" in
*"Missing or invalid DAT"* | \
*"Data file not found"* | \
*"Removal datafile clean.dat not found"* | \
*"Unable to remove viruses"* )
    fail
    ;;
esac
trap EXIT

echo "$OUT"
echo Update OK
# change the current dat file links
run cd $LIBDIR
run ln -sf $VERSION/*.dat .
# remove some crap
run cd $DATDIR
run rm -f *.exe *.tar *.txt

echo
echo Completed OK

# done
