#! /bin/sh 
if [ $# -lt 2 ]; then
   echo "command syntax:"
   echo "   tardi <base-dir> <seg-type> [<min-save>] [<h5-store>]"
   echo " "
   echo "where: "
   echo "<base-dir> Base directory containing gps sub directories, e.g. "
   echo "           '/gds-h1/dmt/triggers/DQ_Segments'"
   echo "<seg-type> gps subdirectory prefix, e.g. 'H-DQ_Segments'. If the"
   echo "           subdirectory is a null string (''), the directory names"
   echo "           are truncated gps values and the file prefix used "
   echo "           for the tar file name is the parent directory name."
   echo "<max-save> if specified, is the maximum number of directories to be "
   echo "           left uncompressed [100]"
   echo "<h5-store> Optional directory to compress to h5 (segments only)"
   exit 1
fi
trig_dir=$1
seg_type=$2
min_save=100
if [ $# -ge 3 ]; then
   min_save=$3
   [ $min_save -lt 10 ] && exit 2
fi
h5store=""
[ $# -ge 4 ] && h5store="$4"
#
#  set up control vbls, etc
now=`when 0 %s`
now_gps=`expr $now / 100000`
sav_gps=`expr $now_gps - $min_save`
cd $trig_dir
[ -n "$h5store" ] && mkdir -p $h5store
#
# get directory names
if [ -n "$seg_type" ]; then
   seg_template="${seg_type}-*/"
   file_base="$seg_type"
else
   seg_template="*/"
   file_base=`echo $trig_dir | sed -e 's,/$,,g' -e 's,^.*/,,g'`
fi
#
# loop over directories
for d in ${seg_template}; do
   if [ ! -d $d ]; then
      continue
   fi
   #
   #  get the subdirectory truncated gps
   noslash=`echo $d | sed -e 's,/$,,g' -e 's,.*/,,g'`
   if [ -n "$seg_type" ]; then
      gps=`echo $noslash | cut -d '-' -f 3`
   else
      gps=`echo $d | sed -e 's,/$,,g'`
   fi
   #
   #  Optionally generate an hdf5 file
   if [ $gps -lt $now_gps -a -n "$seg_type" ]; then
      if [ -n "$h5store" ]; then
         h5f="$h5store/${file_base}-${gps}.h5"
         echo "make hdf file: $h5f"
         if [ ! -f $h5f ]; then
	    seg_calc -c "write -file '$h5f'" \
                     ${seg_type}-${gps}/${seg_type}-*.xml
         fi
      fi
   fi
   #
   # tar the directory
   if [ $gps -lt $sav_gps ]; then
      tarf="${file_base}-${gps}.tar.gz"
      echo "Tar $d"
      tar -czf $tarf $d
      tmpdir=".d-$d"
      mv $d $tmpdir
      rm -r $tmpdir
   fi
done
