#!/bin/bash
# Copyright (c) 1997-now, 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

probs=`/usr/sbin/fix_vm -l | wc -l`
if [ "$probs" -gt "0" ]
then
    echo -n "Found problems before retention check: " >> /var/log/asterisk/fix_vms
    date >> /var/log/asterisk/fix_vms
    /usr/sbin/fix_vm -q
fi

current_number_of_voicemails=0
removed_number_of_voicemails=0

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
  fls=`find /home/services/asterisk/var/spool/asterisk/voicemail/$SHORTNAME/$VMBOX -type f -name msg\* 2>/dev/null | wc -l`
  current_number_of_voicemails=$(($current_number_of_voicemails + $fls))
  if [ "$RETENTION" -gt "0" ]
  then
    fls=`find /home/services/asterisk/var/spool/asterisk/voicemail/$SHORTNAME/$VMBOX \
         -type f -name msg\* -mtime +$RETENTION 2>/dev/null | wc -l`
    removed_number_of_voicemails=$(($removed_number_of_voicemails + $fls))
    if [ "$fls" -gt "0" ]
    then
         echo -n "Removing voicemails past retention time: " >> /var/log/asterisk/fix_vms
         date >> /var/log/asterisk/fix_vms
         find /home/services/asterisk/var/spool/asterisk/voicemail/$SHORTNAME/$VMBOX \
              -type f -name msg\* -mtime +$RETENTION 2>/dev/null >> /var/log/asterisk/fix_vms

         find /home/services/asterisk/var/spool/asterisk/voicemail/$SHORTNAME/$VMBOX \
              -type f -name msg\* -mtime +$RETENTION 2>/dev/null | xargs rm -f
    fi
  fi
done < <(
echo "select distinct voicemailnumber, shortname, vm_retention \
        from phoneline left join company on company.id = phoneline.company \
       where company.status = 'active' and isnumeric(voicemailnumber) \
             and phoneline.status <> 'deleted'" | psql -tqA -F' ' -U astium)

echo "Huidig aantal voicemail berichten: $current_number_of_voicemails" >>/tmp/retention.log
echo "Aantal verwijderde voicemail berichten: $removed_number_of_voicemails" >>/tmp/retention.log
echo "" >>/tmp/retention.log

/usr/sbin/fix_vm -q

