#!/bin/sh

#
# $Id: anyboxadmin,v 1.7 2003/06/07 22:46:30 alan Exp alan $
#


# Script to reduce a mailbox

# SET THE ANYMAILBOX VARIABLE
# $1 = mailbox name

# SET THE CUT DAYS
# $2 = cutdays, eg 15

# Run from crontab.
# Or, perhaps, put a symlink in ~/bin to get it on the path.


##########  user configuration  ####################
MARP_DIR=$HOME/.procmail/marp
##########  end of user configuration  #############
# MARP_MAIL_DIR is needed
. "${MARP_DIR}/userdata.sh"

if [ x${1} != "x" ]; then
  ANYMAILBOX=${1}
else
  exit 1
fi


# let is require to change 0x10 to 16
# [ $(($2)) -ge 0 ] && let CUTDAYS=${2} || CUTDAYS=15
CUTDAYS=15
[ $(($2)) -gt 0 ] && CUTDAYS=${2}
CUTDATE=`date +%s -d "${CUTDAYS:-"17"} days ago"`
# check for bad date
CUTDATE=${CUTDATE:-"Bad date"}

# echo ${CUTDAYS}
# echo ${CUTDATE}


THE_MAILBOX=${MARP_MAIL_DIR}/${ANYMAILBOX}
THE_MAILBOX_TMP=${THE_MAILBOX}.$$

THEPROCMAILRC=${MARP_DIR}/anyboxadmin.rc
THELOG=${MARP_DIR}/${ANYMAILBOX}.log


# Does the file exist?
if [ ! -f "${THE_MAILBOX}" ]; then 
  exit 2
fi



############### functions #########################

tidymailbox()
{
  
  lockfile "${THE_MAILBOX}.lock" "${THE_MAILBOX_TMP}.lock"

  # check for existence of file
  if [ -f "${THE_MAILBOX}" ]; then

    # delete the temporary mailbox if it exists
    rm -f "${THE_MAILBOX_TMP}"

    # remove the temporary folder mailbox lock
    rm -f "${THE_MAILBOX_TMP}.lock"
    # echo "${THE_MAILBOX}.lock removed"


    # Feed each message from the mailbox file to the
    # procmail recipes to filter out old mail.
    < "${THE_MAILBOX}"  formail -Y -s procmail -m "${THEPROCMAILRC}" \
    "${MARP_MAIL_DIR}" "${MARP_DIR}" "${THE_MAILBOX_TMP}" "${THELOG}" ${CUTDATE}
    
    # copy the temp file to the real file
    if [ -f "${THE_MAILBOX_TMP}" ]; then
      cp -f "${THE_MAILBOX_TMP}" "${THE_MAILBOX}"
    else
      # just remove the folder
      rm -f "${THE_MAILBOX}"
      # touch so Pine doesn't get upset if the file is missing
      touch "${THE_MAILBOX}"
      chmod 0600 "${THE_MAILBOX}"
    fi
  else
    # just remove the temporary mailbox lock
    rm -f "${THE_MAILBOX_TMP}.lock"
  fi
  # remove the temp file and the real box lock 
  rm -f "${THE_MAILBOX_TMP}"
  rm -f "${THE_MAILBOX}.lock"
}



############### end of functions ###################


tidymailbox
echo
echo "${ANYMAILBOX} log"
mailstat -tms "${THELOG}"
 

