#!/bin/bash
#
# Cleans up old SMS files/dirs, if there are too many
#

#if more than 1000 files/directories, delete the 100 oldest
MAX_FILES_IN_FOLDER=1000
MAX_FILES_IN_FOLDER_REDUCED=900

SMS_SPOOL_BASE=/tmp/sms

if [ ! -d ${SMS_SPOOL_BASE} ]; then
	exit 0
fi

export IFS=$'\n'

function remove_old_files_from_folder {
	SMSDIR=$1
	[[ ! -d "$SMSDIR" ]] && return
	n=`ls -rt "$1"|wc -l`
	count=0
	
	if [ $n -gt $MAX_FILES_IN_FOLDER ];then
		let deletecount=n-MAX_FILES_IN_FOLDER_REDUCED
		
		for file in `ls -rt "$SMSDIR"`; do
			rm -rf "$SMSDIR"/"$file"
			let count++
			[[ $count -ge $deletecount ]] && break
		done
	fi
}

# remove old files in failout and in, if there are too many delete some of the oldest
remove_old_files_from_folder $SMS_SPOOL_BASE/failout/
remove_old_files_from_folder $SMS_SPOOL_BASE/in/
# remove_old_files_from_folder $SMS_SPOOL_BASE/out/

