#!/bin/sh
#
# @(#)logprune.sh,v 1.3 2004/04/23 06:14:31 kim Exp
#
# Removes old files from a tree structured YYYY/MM/DD (e.g. from roller).
#
# 1996-10-20  Kimmo Suominen
#
PATH=/usr/pkg/sbin:/usr/pkg/bin:/bin:/usr/bin:/usr/sbin
export PATH

oldtime=
noexec=0
verbose=0

usage="Usage: $0 [-d days | -m months] [-v] logdir"
while getopts d:m:nv opt
do
    case "$opt" in
    d)	oldtime="-d $OPTARG"
	forcetime="-m 1"
	;;
    m)	oldtime="-m $OPTARG"
	forcetime="-m `expr $OPTARG + 1`"
	;;
    n)	noexec=1
	;;
    v)	verbose=1
	;;
    *)	echo "$usage" >&2
	exit 1
	;;
    esac
done
shift `expr $OPTIND - 1`
case $# in
0)  echo "$usage" >&2; exit 1;;
*)  ;;
esac
if [ -z "$oldtime" ]
then
    echo "$usage" >&2
    exit 1
fi

olddir=`logtime $oldtime | sed -e 's;\(....\)\(..\)\(..\).*;\1/\2/\3;'`
forcedir=`logtime $forcetime | sed -e 's;\(....\)\(..\).*;\1/\2;'`

rmdirs=
for i
do
    if [ ! -d "$i" ]
    then
	echo "Directory $i does not exist!" >&2
    else
	for j in $olddir $forcedir
	do
	    if [ -d $i/$j ]
	    then
		rmdirs="$rmdirs $i/$j"
		if [ $verbose -eq 1 ]
		then
		    echo "Removing $i/$j"
		fi
	    fi
	done
    fi
done
if [ -z "$rmdirs" ]
then
    if [ $verbose -eq 1 ]
    then
	echo "No directories to remove!"
    fi
else
    if [ $noexec -eq 1 ]
    then
	echo "Need to remove: $rmdirs"
    else
	rm -rf $rmdirs
    fi
fi
