#!/bin/bash
# This script periodically checks the size of a specified
# log file. If the file size exceeds a specified maximum, then
# the log is moved to a backup location.

if [ ! -n "$3" ]
then
  echo "usage: `basename $0` logfile maxBytes sleepSec"
  exit 1
fi

# This is the logfile to check
logfile=$1

# Create the log file backup directory
if [ ! -e /mnt/hda/logs ]; then
  mkdir /mnt/hda/logs
fi

# This is where to move the log
backupLogfile=/mnt/hda/logs/`/usr/bin/basename $logfile`.bak

# Move logfile when size exceeds maxsize bytes
maxsize=$2

# Sleep this many seconds between checking the file size
sleeptime=$3

# Keep track of how many times file has been moved
nMoves=0

while [ 1 ]
do

  if [ -f $logfile ]; then
    let filesize=`ls -l $logfile | sed -f /etc/siam/fs.sed`

    if [ "$filesize" -gt "$maxsize" ] 
    then 
      let nMoves="$nMoves+1"
      echo "New file number $nMoves started at " `date` > $backupLogfile
      # Copy logfile to backupLogfile and truncate logfile
      cat $logfile >> $backupLogfile && > $logfile
    fi     
  fi       # logfile exists

  /bin/sleep $sleeptime

done
