#! /bin/sh
# $Cambridge: hermes/src/prayer/utils/prayer-cyclog.SRC,v 1.3 2008/09/16 10:00:08 dpc22 Exp $

suffix=gz

# Following is correct for Linux.
compress="/bin/gzip"
chown="/bin/chown"
chgrp="/bin/chgrp"
mv="/bin/mv"
rm="/bin/rm"

cycle_log () {
    dir=$1
    user=$2
    group=$3
    log=$4
    keep=$5

    file=$dir/$log

    if [ $keep -lt 10 ]; then keept=0$keep; else keept=$keep; fi;

    if [ -f $file.$keept ]; then $rm $file.$keept; fi;
    if [ -f $file.$keept.$suffix ]; then $rm $file.$keept.$suffix; fi;

    while [ $keep -gt 1 ]; do
        old=`expr $keep - 1`
        if [ $old -lt 10 ]; then oldt=0$old; else oldt=$old; fi;

        if [ -f $file.$oldt ]; then
            $mv $file.$oldt $file.$keept
            $compress $file.$keept
            $chown $user $file.$keept.$suffix
            $chgrp $group $file.$keept.$suffix
        elif [ -f $file.$oldt.$suffix ]; then
            $mv $file.$oldt.$suffix $file.$keept.$suffix
            $chown $user $file.$keept.$suffix
            $chgrp $group $file.$keept.$suffix
        fi
        keep=$old
        keept=$oldt
        done

    if [ -f $file ]; then
        $mv $file $file.01
        $chown $user $file.01
        $chgrp $group $file.01
    fi
}    

cycle_log "__VAR_PREFIX__/logs" "prayer" "prayer" "access_log"     28
cycle_log "__VAR_PREFIX__/logs" "prayer" "prayer" "session_log"    28
cycle_log "__VAR_PREFIX__/logs" "prayer" "prayer" "prayer"         28
cycle_log "__VAR_PREFIX__/logs" "prayer" "prayer" "prayer_session" 28
