#!/bin/sh
##---------------------------------------------------------------------------##
##  File:
##	$Id: filter-spool,v 1.6 2002/03/12 22:30:26 ehood Exp $
##  Description:
##	Script to grab mail spool and filter mail to raw mbox archives.
##---------------------------------------------------------------------------##
##  Copyright (C) 2001-2002	Earl Hood <earl@earlhood.com>
##  Script derived from example provided in the Procmail documention.
##
##  This program is free software; you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation; either version 2 of the License, or
##  (at your option) any later version.
##  
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##  
##  You should have received a copy of the GNU General Public License
##  along with this program; if not, write to the Free Software
##  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
##  02111-1307, USA
##---------------------------------------------------------------------------##

PATH=$HOME/bin:/usr/local/bin:/usr/bin:/bin; export PATH
BASEDIR=`dirname $0`
archiveroot_rel=$BASEDIR/..

# Verify root of installation
ARCHIVEROOT=`cd $archiveroot_rel && pwd`
if [ "X$ARCHIVEROOT" = "X" ]; then
  echo "Cannot determine archive root!"
  exit 1;
fi
if [ ! -d $ARCHIVEROOT ]; then
  echo "$ARCHIVEROOT is not a directory!"
  exit 1;
fi

# Load configuration
. $ARCHIVEROOT/lib/config.sh

# Make sure umask is set to make things readable by default
umask 022

# Make sure certain directories exist
mkdir -p $ARCHIVEROOT/mbox
mkdir -p $ARCHIVEROOT/html
mkdir -p $ARCHIVEROOT/log

# Process mail spool
if cd $ARCHIVEROOT &&
 test -s $ORGMAIL &&
 lockfile -r0 -l1024 .newmail.lock 2>/dev/null
then
  trap "rm -f .newmail.lock" 1 2 3 13 15
  if [ "$IS_MAIL_SPOOL" = "1" ]; then
    lockfile -l1024 -ml
  else
    lockfile -l1024 $ORGMAIL.lock
  fi
  /bin/cat $ORGMAIL >>.newmail &&
      /bin/cat /dev/null >$ORGMAIL
  if [ "$IS_MAIL_SPOOL" = "1" ]; then
    lockfile -mu
  else
    /bin/rm -f $ORGMAIL.lock
  fi
  formail -s procmail $ARCHIVEROOT/.procmailrc $PROCMAILVARS <.newmail && \
      /bin/rm -f .newmail
  /bin/rm -f .newmail.lock
  exit 0
else
  exit 1
fi
