#!/bin/sh

before="$(date +%s)"

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

if [ $# -eq 0 ]; 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 [ $# -eq 1 ]; then

	cd $LOG_ARCH_DIR
	if [ $? -ne 0 ]; then
		exit 1
	fi
	
	cd $LOG_ARCH_DIR && /bin/tar -ch * 2> /dev/null
	exit 0
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 0
