#!/usr/pkg/bin/bash
#
#   logtail.sh  --  part of LogRider package
#
#   Dump tail of given logfile from saved position
#   and update approprited data in <logfile>.offset
#
#   Uses external commands:
#      dd, stat -lt, echo -e.
#
#   Written by <evseev@ucvt.ru> at Jan 2003.
#   Distributed under terms of GNU GPL.
#

function error_exit()
{
	exit_code=$1
	shift
	echo "Error: $*, exit" 1>&2
	exit $exit_code
}

function report_warning() {
	echo "Warning: $*" 1>&2
}

function final_things()
{
	[ -z "$SAVED_INODE" ] && SAVED_INODE=0
	[ -z "$SAVED_POS"   ] && SAVED_POS=0

	set abc `stat -f "%z %i" $LOGFILE`
	ACTUAL_LOGSIZE=$2
	ACTUAL_INODE=$3
	$doit : $2, logsize=$ACTUAL_LOGSIZE, inode=$ACTUAL_INODE

	[ -z "$ACTUAL_LOGSIZE" ] && ACTUAL_LOGSIZE=0
	[ -z "$ACTUAL_INODE"   ] && ACTUAL_INODE=0

	if [ $ACTUAL_INODE -eq $SAVED_INODE -a $SAVED_POS -gt $ACTUAL_LOGSIZE ]; then
		report_warning "log file $LOGFILE is smaller than last time checked (may be tampered?)"
		SAVED_POS=0
	fi

	if [ $ACTUAL_INODE -ne $SAVED_INODE -o $SAVED_POS -gt $ACTUAL_LOGSIZE ]; then
		SAVED_POS=0
	fi

	dd if=${LOGFILE} ibs=${SAVED_POS} skip=1 2> /dev/null

	echo -e "${ACTUAL_INODE}\n${ACTUAL_LOGSIZE}" > $OFFSET_FILE
}

if [ "$1" = "-d" ]; then
	shift
	doit=echo
fi

if [ "$#" -ne 1 ]; then
	echo Usage: logtail.sh logfile
	exit 1
fi

LOGFILE=$1
OFFSET_FILE=${LOGFILE}.offset

if [ ! -r $LOGFILE ]; then
	error_exit 2 "cannot read $LOGFILE"
fi

if [ -r $OFFSET_FILE ]; then
	( while read line; do
		$doit : line = $line
		if [ -z "$SAVED_INODE" ]; then
			SAVED_INODE=$line
			$doit : set SAVED_INODE
		elif [ -z "$SAVED_POS" ]; then
			SAVED_POS=$line
			$doit : set SAVED_POS
		else
			$doit : break..
			break
		fi
	done
	final_things ) < $OFFSET_FILE
else
	final_things
fi

## EOF ##
