#!/bin/sh
# --------------------------------------------------------------------------
# Copyright 1992-1994 by Forschungszentrum Informatik (FZI)
# All rights reserved.
#
# You can use and distribute this software under the terms of the license
# you should have received along with this software; either version 1.1 of
# the license, or (at your option) any later version.
# For a copy of the license or for additional information about this software,
# write to Xcc Software, Durlacher Allee 53, D-76131 Karlsruhe, Germany;
# Email: obst@xcc-ka.de.
# --------------------------------------------------------------------------
# 'obst-cct - 27:02:91 - Dietmar Theobald'
#
# obst-cct [-l [<delay>]] [-c] [-e]
#
# Clean container directory: remove empty containers and squeeze nonempty ones
# in $OBSTCONTAINER.
# If the option '-l' is enabled the removal/squeeze is repeated every <delay>
# seconds. The default value for <delay> is 300s, i.e. 5min.
#
 self='obst-cct'
usage='[-l [<delay>]] [-c] [-e]'
[ -n "$OBSTdir" ] || { OBSTdir="`cd \`dirname $0\`;pwd`/"; export OBSTdir; }

sync_container=2
    shrink_opt='-s'
    shrink_txt='squeez'
          echo=

if [ -n "$OBSTCONTAINER" ] ; then
  cd $OBSTCONTAINER
elif [ -n "$SOSCONTAINER" ] ; then
  cd $SOSCONTAINER
else
  echo >&2 "*** $self: environment variable OBSTCONTAINER not defined"
  exit 1
fi

while [ $# -gt 0 ]; do
   case "$1" in
      -l) loop='+'; shift
	  if [ $# -gt 0 ] ; then
	     delay="$1"; shift
	  else
	     delay='3600'
	  fi			;;
      -c) shrink_opt='-c'
	  shrink_txt='compress'	;;
      -e)       echo='+'	;;
       *) break			;;
   esac
   shift
done

[ $# -le 0 ] || { echo >&2 "*** usage: $self $usage"; exit 1 ;}

while [ 1 ]
do
   for cnt in *[0-9]
   do
      [ -f "$cnt" -a "$cnt" != "$sync_container" ] && {
	 [ "$echo" ] && {
	    echo "$self: ${shrink_txt}ing container $cnt ..."
	    sz_old="`ls -Ls $cnt | sed 's|^[^0-9]*\([0-9]*\).*|\1|'`"
	 }
         ${OBSTdir}cnt -t $shrink_opt $cnt 2> /dev/null
         ${OBSTdir}cnt -t -d	     $cnt 2> /dev/null

	 [ "$echo" ] && {
	    if [ -s $cnt ]; then
	       sz_new="`ls -Ls $cnt | sed 's|^[^0-9]*\([0-9]*\).*|\1|'`"
	    else
	       sz_new=0
	    fi
	    echo "$self: ${shrink_txt}ed  container $cnt from $sz_old to $sz_new [blocks]"
	 }
      }
   done

   [ "$loop" ] || break

   sleep $delay
done
