#!/bin/sh
#  $Id: decay,v 1.9 2015-03-31 12:24:04 pc161604 Exp $
#  Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Component: Billing
#  Author: duncans
#
#  Aggregate small files into larger ones and delete the originals.
#

## first argument is the tarantella dir
TTADIR="$1"
if [ ! -d "$TTADIR" ]; then
  echo "$0: Top level Tarantella directory missing: $TTADIR" 1>&2
  exit 1
fi

## throw away this argument now
shift

## move to the correct directory
if [ ! -d "$1" ]; then
  echo "$0: Top level billing directory missing: $1" 1>&2
  exit 2
fi
cd $1

## remove any old log file
logfile="$1/decay.log"
rm -f $logfile

## locate tcl
tcl=/usr/bin/tclsh
if [ ! -x "$tcl" ]; then
  echo "$0: Failed to locate tcl interpreter: $tcl" 1>>$logfile
  exit 3
fi

## locate the tcl script
tclscript=$TTADIR/bin/scripts/decay.tcl
if [ ! -f "$tclscript" ]; then
  echo "$0: Failed to locate tcl script: $tclscript" 1>>$logfile
  exit 4
fi

## make sure any old files are upgraded to the new names
$tcl $tclscript --upgrade $2 $3 $4 1>$logfile 2>&1
exitval="$?"
if [ "$exitval" != "0" ]; then
  echo "$0: Failed to upgrade old style billing files: $tcl $tclscript --upgrade $2 $3 $4" 1>>$logfile
  exit $exitval
fi

## move minutes to hours
$tcl $tclscript --decay $2 $3 $5 1>$logfile 2>&1
exitval="$?"
if [ "$exitval" != "0" ]; then
  echo "$0: Failed to move minute files to hour file: $tcl $tclscript --decay $2 $3 $5" 1>>$logfile
  exit $exitval
fi

## move hours to days
$tcl $tclscript --decay $3 $4 $6 1>>$logfile 2>&1
exitval="$?"
if [ "$exitval" != "0" ]; then
  echo "$0: Failed to move hour files to day file: $tcl $tclscript --decay $3 $4 $6" 1>>$logfile
  exit $exitval
fi

## delete old billing files if we're past the limit
$tcl $tclscript --archive $4 $7 1>>$logfile 2>&1
exitval="$?"
if [ "$exitval" != "0" ]; then
  echo "$0: Failed to archive old files: $tcl $tclscript --archive $4 $7" 1>>$logfile
  exit $exitval
fi


## remove the logfile
/bin/rm -f $logfile

## it all worked fine
exit 0
