#!/bin/ksh

# The logtail program written in ksh.

input_file=$1
offset_file=$2

inode=-1  # Not to ever be true
ino=-1	  # Also Not ever true

offset=0
lines=0

if [ -z "$offset_file" ] ; then
	directory_path=$(dirname $input_file)
	file_name=${input_file##*/}
        offset_file=$directory_path/.${file_name}.offset
else
	directory_path=$(dirname $input_file)
	file_name=${input_file##*/}
fi

if [ ! -f $input_file -a ! -r $input_file ] ; then
         printf "The input file $input_file does not exist or is unreadable\n";
         exit 66
else
	if [ -f $offset_file ]; then
		while read line
		do 
		   	if [ -z $line ] ; then continue ; fi
		   	set -A offset_data $line
        		ino=${offset_data[0]}
        		lines=${offset_data[1]}
		done < $offset_file
	else
		touch $offset_file
		ino=-1
	fi
fi

inode=`ls -i $input_file| awk '{ print $1 }'`

filelength=`wc -l $input_file| awk '{ print $1 }'`

if [ $inode -ne $ino ] ; then
    if [ $offset -eq $filelength ] ; then exit ; fi
    if [ $offset -gt $filelength -a $offset -ne -1 ] ; then
        offset=0
        printf "***************\n";
        printf "*** WARNING ***: the file $input_file shrank since last checked!\n";
        printf "*************** This could indicate tampering.\n";
    fi
fi

if [ $inode -ne $ino -o $offset -gt $lines ]; then
        offset=0;
fi

tail +$lines $input_file >$input_file.logtail

linecount=`wc -l $input_file.logtail|awk '{ print $1 }'`

(( lines = lines + linecount + 1 ))

if [ ! -w $offset_file ]; then
        printf "File $offsetfile cannot be created. Check your permissions.\n";
        exit 73;
fi

chmod 600 $offset_file >/dev/null 2>&1
if [ $? -ne 0 ]; then
        printf "Cannot set permissions on file $offsetfile\n";
        exit 65;
fi

rm -f $offset_file
printf "$inode $lines\n" >$offset_file

cat $input_file.logtail
rm -f $input_file.logtail

exit 0;
