#!/bin/sh

FILE="$1"
APP="$2"

if [ -z "$FILE" ] || [ -z "$APP" ]
then
	echo "USAGE: $0 FILE APP" >&2
	exit 1
fi

if [ "x$FILE" != "x-" ] && ! [ -f "$FILE" ]
then
	echo "FILE $FILE does not exist" >&2
	exit 1
fi

[ -d "/tmp/tailnew/$APP" ] || mkdir -p "/tmp/tailnew/$APP"

OLD_END=0
if [ -f "/tmp/tailnew/$APP/end" ]
then
	OLD_END=$(cat "/tmp/tailnew/$APP/end")
fi

if [ "x$FILE" = "x-" ]
then
	FILE="/tmp/tailnew/$APP/tempfile"
	while read cache ; do
		echo $cache >> "/tmp/tailnew/$APP/tempfile"
	done
fi

END=$(wc -l "$FILE" | awk '{print $1}')
LINES=$(($END - $OLD_END))

echo $END > "/tmp/tailnew/$APP/end"

tail -n$LINES "$FILE"

[ -f "/tmp/tailnew/$APP/tempfile" ] && rm -f "/tmp/tailnew/$APP/tempfile"
