#!/bin/bash

## sarulesupdate : v0.01

## tkooda : 2004-07-28 : updates local spamassassin rules
##  - reads pairs of filenames / urls from the rules file.
##  - tests new rulefiles and installs them if they have valid syntax
##  - returns the number of newly installed rulefiles (w/valid syntax)

## INSTALL:
##  - `mkdir -p /etc/sarulesupdate/tmp`
##  - `ln -s /etc/mail/spamassassin /etc/sarulesupdate/installed`
##  - put rules into /etc/sarulesupdate/rules

## USAGE:
##  - `sarulesupdate || /etc/init.d/spamassassin restart`

## NOTES:
##  - be carefull when picking the names of the rulefiles so that you don't
##    overwrite other local config files in /etc/mail/spamassassin


SARULES="/etc/sarulesupdate/rules"
SARULEDIR="/etc/sarulesupdate/installed"
SARULETMP="/etc/sarulesupdate/tmp"
WGET="wget"
SA="spamassassin"

function die { echo "$1"; exit 1; }
function out { echo "sarulesupdate: $1"; } # to differ from sa output

[ -f "$SARULES" ] || die "Error: invalid rule file: $SARULES"
[ -d "$SARULEDIR" ] || die "Error: invalid rule dir: $SARULEDIR"
[ -d "$SARULETMP" ] || die "Error: invalid rule temp dir: $SARULETMP"
[ -x "`which $WGET`" ] || die "Error: could not find executable: $WGET"
[ -x "`which $SA`" ] || die "Error: could not find executable: $SA"

count=0
while read name url; do
  [ "$name" == "local.cf" ] && die "Error: cannot overwrite local.cf"
  echo "$name" |grep '/' >/dev/null && die "Error: invalid name: $name"
  wget -q -N -O "$SARULETMP/$name" "$url" 2>/dev/null
  if ! cmp "$SARULETMP/$name" "$SARULEDIR/$name" 1>/dev/null 2>&1; then
    if $SA --lint --prefspath="$SARULETMP/$name"; then
      cp -af "$SARULETMP/$name" "$SARULEDIR/$name.tmp.sarulesupdate" \
        && mv -f "$SARULEDIR/$name.tmp.sarulesupdate" "$SARULEDIR/$name" \
        && out "installed new rules: $name" \
        && let count++
    else
      out "ignored invalid rules: $name"
    fi
  fi
done < <(cut -d'#' -f1 "$SARULES" |grep '\w') # to preserve $count

exit $count

