#!/bin/sh

before="$(date +%s)"

LOGGER="/bin/logger -t $0"

if [ $# -le 1 ]; then
    echo "Usage: $0 sourceLogDir tmpDestDir [sourceSubdir1] [sourceSubdir2] ..."
    exit
fi

OLDDIR=`pwd`
LOG_ARCH_DIR=$1
DEST_DIR=$2

stat $LOG_ARCH_DIR > /dev/null 2>&1
if [ $? -ne 0 ]; then
    exit 1
fi

if [ -d $DEST_DIR ]; then
    rm -rf $DEST_DIR
fi

mkdir $DEST_DIR

cd $LOG_ARCH_DIR
if [ $? -ne 0 ]; then
    exit 1
fi

archivedFile="*.tar.gz"

if [ $# -gt 2 ]; then
  shift 2
  argsdirs=$(echo $* | sed -e 's/[ ]/\\|/g')
  for log in $( find $LOG_ARCH_DIR/* -type f | grep $argsdirs | xargs stat -c "%Y %n" | sort -n | cut -d ' ' -f 1 --complement )
do
    if [[ $log == $archivedFile ]]; then
		curlogdir=$(dirname $log)
		tar -xf $log -C $curlogdir
		if [ $? -eq 0 ]; then
			find $curlogdir/* -type f -not -name "$archivedFile" | xargs stat -c "%Y %n" | sort -n | cut -d ' ' -f 1 --complement | xargs -d '\n' /bin/catdst -d $DEST_DIR
			find $curlogdir -type f \( -not -name "$archivedFile" -not -name 'z' \) -print0 | xargs -0 -I {} rm {}
		fi
    else
		/bin/catdst -d $DEST_DIR $log
    fi
done

else
	for log in $( find $LOG_ARCH_DIR/* -type f | xargs stat -c "%Y %n" | sort -n | cut -d ' ' -f 1 --complement )
	do
		if [[ $log == $archivedFile ]]; then
			curlogdir=$(dirname $log)
			tar -xf $log -C $curlogdir
			if [ $? -eq 0 ]; then
				find $curlogdir/* -type f -not -name "$archivedFile" | xargs stat -c "%Y %n" | sort -n | cut -d ' ' -f 1 --complement | xargs -d '\n' /bin/catdst -d $DEST_DIR
				find $curlogdir -type f \( -not -name "$archivedFile" -not -name 'z' \) -print0 | xargs -0 -I {} rm {}
			fi
		else
			/bin/catdst -d $DEST_DIR $log
		fi
	done
fi

# calculate the elapsed time for job
#
after="$(date +%s)"
elapsed_seconds="$(expr $after - $before)"
$LOGGER "Elapsed time for gathering logs: "$elapsed_seconds "sec."

cd $DEST_DIR && /bin/tar -ch * 2> /dev/null
cd $OLDDIR

exit

do_arch=0

for arg in $(stat -c "%Y %n" * | sort -n | cut -d ' ' -f 1 --complement)
    do
    do_dir=$(echo "$*" | grep "$arg")
    if ([ $# -le 2 ] || [ "$do_dir" != "" ] ); then
	{
	    for log in $(find $arg -type f | sort -n)
	    do
		  size=$(stat -c %s $log)
		  do_arch=1
		  if [ $size -gt 0 ]; then
			if [ "$LOG_ARCH_DIR" = "/var/log/Archive/" ]; then
		  	  echo "<-"$(dirname $log | sed 's/\// /g')"->" >> $DEST_DIR/$(basename $log)
			else
			  echo "<-"$(basename $LOG_ARCH_DIR) $(dirname $log)"->" >> $DEST_DIR/$(basename $log)
			fi
		    cat $log >> $DEST_DIR/$(basename $log)
		  fi
	    done
	}
    fi
done

if [ $do_arch -eq 1 ]; then
  cd $DEST_DIR && /bin/tar -ch * 2> /dev/null
fi

cd $OLDDIR

exit
