#!/bin/sh
##############################################################################
# This script is in the public domain
#
# Written by Pierre Habouzit <madcoder@debian.org>
##############################################################################

init () {
    export LC_ALL=C
    export LANG=C
    export LANGUAGE=C

    tmp=`mktemp -td clamav.XXXXXX` || exit 1
}

fini () {
    rm -rf $tmp
    # or with etch's clamav:
    /usr/sbin/invoke-rc.d clamav-daemon reload-database > /dev/null
}

getfile () {
    url="$1"
    tout="$tmp/$2"
    out="${2%.gz}"

    # Get the file with curl
    # --remote-time asks curl to set the time of the file to the time given by the web server
    # --time-cond asks curl to get the file only if it is more recent that the reference file previously downloaded
    if test -f $out; then
        curl --remote-time --time-cond $out --silent --output $tout $url || return 1
    else
        curl --remote-time --silent --output $tout $url || return 1
    fi

    if test -s $tout; then
        if test "$2" = "$out"; then
            gcmd=grep
        else
            gcmd=zgrep
        fi
        if test "$out" != "${out%.hdb}"; then
            regex='^[a-z0-9]*:[0-9]*:[^:]*$'
        else
            regex='^[^:]*:[0-9]*:\*:[^:]*$'
        fi
        # Keep only correct lines
        $gcmd $regex $tout > ${out}.tmp || return 1
        # Recover the time set by curl from the downloaded file before overriding the file
        touch --reference=$tout ${out}.tmp || return 1
        # set the correct user before overriding the file
        chown clamav:clamav ${out}.tmp || return 1
        # Atomically replace the current file if everything was OK
        mv --force ${out}.tmp ${out} || return 1
    fi
    return 0
}

init
trap fini 0

cd /var/lib/clamav || exit 1

for file in scam.ndb.gz phish.ndb.gz phishtank.ndb.gz; do
    #getfile http://www.sanesecurity.com/clamav/$file $file || echo "error downloading file $file"
    getfile http://mirrors.dotsrc.org/clamav-sanesigs/$file $file $file || echo "error downloading file $file"
done

for file in MSRBL-SPAM.ndb MSRBL-Images.hdb; do
    getfile http://download.mirror.msrbl.com/$file $file || echo "error downloading file $file"
done

trap - 0
fini
exit 0

