#!/usr/local/bin/bash
# voicemail_clean.sh: cleans up deleted voicemail messages older than n days.
# where a day is defined as a 24 hour period.
# If a message has been deleted, restored, saved or moved in some other 
# way before it was deleted last time, only the last delete date will 
# be used in determining the age of this message.
 
# Use the config settings from the $CONFIG_DEFS file
CONFIG_DEFS="/usr/local/etc/sipxpbx/config.defs"
[ ! -f "${CONFIG_DEFS}" -o -z "${CONFIG_DEFS}" ] && die "Could not find file: ${CONFIG_DEFS}"
 
# Source $CONFIG_DEFS to set $SIPXCHANGE_DOMAIN_NAME for use below.
source $CONFIG_DEFS
 
MAILSTORE_DIR=/var/sipxdata/mediaserver/data/mailstore
DAYS=${VOICEMAIL_AGE_LIMIT}

# Override the DAYS variable with optional command line argument
if [ "$1" == "--days" ]; then
  if [[ "$2" == [1-9] ]]; then
    if [[ "$2" < "$DAYS" ]]; then
      DAYS=$2
    fi
  fi
fi
 
if [ -d ${MAILSTORE_DIR} ]
then 
    for deleted_dir in `find ${MAILSTORE_DIR} -type d -name deleted -maxdepth 2`
    do
        if cd "${deleted_dir}"
        then
            # Find all voice messages that are more than $DAYS old.  Base the test
            # on the last modified date for the voice message "envelope" file.        
            count=0
            for name_prefix in `find . -mtime +${DAYS} -name "*-*.xml" | cut -d - -f 1`
            do
                # Remove all files with a .sta, .wav or .xml extension that have the
                # same filename prefix as the old voice message envelope.
                rm -f ${name_prefix}-*.{sta,wav,xml}
                let count++
            done
        
            if [ $count -gt 0 ]
            then
                # Now that we've deleted messages, the summary.xml file is no longer
                # accurate.  Delete it so that it gets recreated next time it is accessed.
                rm -f summary.xml
            fi
        else
            echo "failed to cd to '${deleted_dir}'" 1>&2
        fi
    done
 
else
    echo "Mailstore '${MAILSTORE_DIR}' not found" 1>&2
    exit 1
fi
