#!/bin/bash
# Copyright (c) 1997-2009, NeoNova BV, The Netherlands. All rights Reserved.
#
# This software is the copyrighted work of NeoNova BV.
# Use of the software is subject to the general business terms and conditions of NeoNova BV
# and its related transaction documents like license sheets or other written notices.
#
# Any reproduction or redistribution of the software not in accordance with the license terms
# is expressly prohibited by law, and may result in severe civil and criminally penalties.
# Violators will be prosecuted to the maximum extent possible.
#
# This cron script goes to every voicemailbox, and deletes messages that are too old

MAX_RETENTION=`echo "select value from astglobals where name = 'vm_retention'" | psql -tqA -F' ' -U astium`
if [ -z "$MAX_RETENTION" ]
then
  MAX_RETENTION=0
fi

if [ "$MAX_RETENTION" -lt "1" ]
then
  logger -i -t `basename $0` "problem retrieving vm_retention value"
  exit 1
fi

echo "select distinct voicemailnumber, shortname, vm_retention \
        from phoneline left join company on company.id = phoneline.company \
       where company.status = 'active' and voicemailnumber > 0 \
             and phoneline.status <> 'deleted'" | psql -tqA -F' ' -U astium | 
while read VMBOX SHORTNAME RETENTION
do
  if [ -z "$RETENTION" ]
  then
    RETENTION=0
  fi
  if [ "$RETENTION" -gt "$MAX_RETENTION" ]
  then 
    RETENTION=$MAX_RETENTION
  fi
  #echo VMBOX=$VMBOX SHORTNAME=$SHORTNAME RETENTION=$RETENTION
  if [ "$RETENTION" -gt "0" ]
  then
    find /home/services/asterisk/var/spool/asterisk/voicemail/$SHORTNAME/$VMBOX \
         -type f -name msg\* -mtime +$RETENTION 2>/dev/null | xargs rm -f
  fi
done

