#!/bin/sh

VAR=.
NOVAR=/var

if [ x$VAR = x$NOVAR ]
then
VAR=@prefix@/var
fi


PID=cachelogd.pid
SPLITTER=splitter.exe

HUP=0
PRESPLIT=0
SPLIT=0

usage()
{
	cat <<EOF
Usage: $0 [OPTIONS]
Options:
	[-k]	[--hup]		Send -HUP signal to cachelogd
	[-p]	[--prepare]	Prepare logs
	[-s]	[--split]	Split logs
	[-h]	[--help]	Display this page

Configuration:
        Base dir: $VAR
        Pid file: $PID
EOF
	exit $1
}

rename_logs()
{
	for LOG_NAME in `ls *.del`
	do
		mv $LOG_NAME $LOG_NAME.done
	done

	for LOG_NAME in `ls *.wrd`
	do
		mv $LOG_NAME $LOG_NAME.done
	done
}

if test $# -eq 0; then
	usage 1 1>&2
fi

while test $# -gt 0; do

	case $1 in
	-k)
		HUP=1
		;;
	--hup)
		HUP=1
		;;
	-p)
		PRESPLIT=1
		;;
	--prepare)
		PRESPLIT=1
		;;
	-s)
		SPLIT=1
		;;
	--split)
		SPLIT=1
		;;
	*)
		usage 1 1>&2
		;;
	esac
	shift
done

if [ x$HUP = x1 ]
then
	echo "Sending -HUP signal to cachelogd..."
	# Check whether cachelogd is running
	if [ -s $PID ]
	then
		# Send HUP signal to cachelogd process
		PROC=`cat $PID`
		killcachelogd $PROC 1

		# Check whether kill didn't fail
		if [ x$? = x1 ]
		then
			echo "kill -HUP $PROC failed."
			exit 1
		fi
		echo "Done"
	else
		echo "$PID is empty or doesn't exist!"
		echo "Check that cachelogd is running."
		exit 1
	fi
fi


if [ x$PRESPLIT = x1 ]
then
	# Presplit logs
	echo "Preparing logs..."
	$SPLITTER -p
	echo "Renaming logs..."
	cd $VAR/raw
	rename_logs
	echo "Done"
fi


if [ x$SPLIT = x1 ]
then
	# Split logs
	echo "Runnig splitter..."
	$SPLITTER
	echo "Deleting logs..."
	cd $VAR/splitter
	rm *.log
	echo "Done"
fi
