#!/bin/sh
logdir=/usr/local/squid/logs/
n_rotate=5
timelimit=`expr 3 \* 60 \* 60` # 3 hours gzip timelimit

# Rotate
#  log         -> log.0
#  log.0[.gz]  -> log.1[.gz]
#  log.1[.gz]  -> log.2[.gz]
#  .. up to n_rotate
do_rotate() {
  log=$1
  n=$n_rotate
  while [ $n -gt 0 ]; do
    np=`expr $n - 1`
    if [ -f $logdir/$log.$np.gz ]; then
       mv $logdir/$log.$np.gz $logdir/$log.$n.gz
    fi
    if [ -f $logdir/$log.$np ]; then
       mv $logdir/$log.$np $logdir/$log.$n
    fi
    n=$np
  done
  if [ -f $logdir/$log ]; then
    mv $logdir/$log $logdir/$log.0
  fi
}

# Compress log.0, with timelimit
do_compress() {
  log=$1
  if [ -f $logdir/$log.0 -a ! -f $logdir/$log.0.gz ]; then
    nice gzip $logdir/$log.0 &
    gzip_pid=$!
    watch_compress $log $gzip_pid &
    watch_pid=$!
    trap "kill $gzip_pid; kill $watch_pid; exit" SIGHUP SIGINT SIGTERM
    wait $gzip_pid
    kill $watch_pid
  fi
}
watch_compress() {
  log=$1
  pid=$2
  sleep $timelimit &
  trap "kill $!;exit" SIGINT SIGHUP SIGTERM
  wait $!
  kill $pid
  logger -t squid -p local4.warning "Compression of $log did not finish in timely manner"
  sleep 100
}


# wait for a log to be reopened
wait_for_log() {
  log=$1
  n=60
  while [ $n -gt 0 -a ! -f $logdir/$log ]; do
    sleep 5
    n=`expr $n - 1`
  done
  if [ ! -f $logdir/$log ]; then
    logger -t squid -p local4.warning "Warning! $logdir/$log did not reappear after rotate!"
  fi
}
###
# Main program
###

# Rotate existing logs
do_rotate access.log
do_rotate cache.log
do_rotate store.log

# Tell Squid that the files has been rotated
/usr/local/squid/bin/squid -k rotate

# Wait for Squid to reopen the log files
wait_for_log access.log

# Compress the old log files
do_compress access.log
do_compress cache.log
do_compress store.log


