#!/bin/bash
# TMDA Maintenance
# Go through the list of users and generate a TMDA PENDING list for any
# user that is using TMDA (has a .tmda/config file)
#
DEBUG=0
DOIT=1
DAYLIMIT='14'
DATE=`date '+%b %d, %Y'`
HOSTNAME=`hostname`
IFS=":";
getent passwd |
(
while read LOGINID PASSWD PUID PGID NAME HOME USERSHELL
   do
   if [ -f $HOME/.tmda/config ]; then
      EMAIL="$LOGINID@$HOSTNAME"
      LOCKFILE="/var/tmp/tmda-pending.$LOGINID.lock"

      if [ "$DEBUG"x != "0"x ]; then
         echo "Processing $EMAIL"
      fi

      # Create qmail tmda extension address if it doesn't exist.
      if [ ! -f $HOME/.qmail-tmda-default ]; then
        echo "| /usr/sbin/tmda-mail-proc" > $HOME/.qmail-tmda-default
      fi

      if [ "$DOIT"x = "1"x ]; then
         # silently and immediately delete all messages older than DAYLIMIT days
         /bin/su - $LOGINID --command="cd $HOME/Maildir/.Pending && find cur new tmp -type f -mtime +$DAYLIMIT -delete"

         # mail a summary report of all new pending messages
         /bin/su - $LOGINID --command="setlock -n -X $LOCKFILE /usr/sbin/tmda-pending-mail \"$NAME\" $LOGINID $HOSTNAME"
         if [ $? != "0" ]; then
           echo "Can't set lock \"$LOCKFILE\".  Exiting."
         fi
         rm -rf $LOCKFILE
      fi

      # If there is a delivery error, notify me
      FAILURE_NOTICE=$HOME/TMDA_DELIVERY_FAILURE
      SUBECT="TMDA DELIVERY FAILURE ($DATE)"
      if [ -f $FAILURE_NOTICE ]; then
        mail -s "$SUBJECT" $EMAIL < $FAILURE_NOTICE
        rm -f $FAILURE_NOTICE
      fi

      # Rotate the .tmda/incoming.log file.
      day=$DAYLIMIT
      while [ "$day"x != "0"x ];
      do
        printday=`printf "%02d" $day`
        currentfile="$HOME/.tmda/incoming.log.$printday"
        if [ "$day"x != "1"x ]; then
          previousnum=`expr $day - 1`
          previousnum=`printf "%02d" $previousnum`
          previousfile="$HOME/.tmda/incoming.log.$previousnum"
        else
          previousfile="$HOME/.tmda/incoming.log";
        fi
        if [ -f $previousfile ]; then
          mv $previousfile $currentfile
        fi
      day=`expr $day - 1`
      done
   else
     # Remove qmail tmda extension address because .tmda does not exist.
     if [ -f $HOME/.qmail-tmda-default ]; then
       rm -f $HOME/.qmail-tmda-default
     fi
   fi
   done
)
