#!/bin/sh
#
# TaRyFikator by Maciej Korze <eaquer@ceti.pl>
#
# $Id: trf,v 1.16 2003/02/02 14:06:11 eaquer Exp $
#
#    Copyright (C) 2002  Maciej Korzen
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

version="0.1"
logfile=~/.trf
state=none
pstate=none

version() {
	echo "TRF $version by Maciej Korze <eaquer@ceti.pl>"
	exit 1
}

usage() {
	echo "Uycie: trf [-d] [-V] [-f plik_z_logiem]"
	echo "	-d			wcza debugowanie"
	echo "	-V			wywietla wersj programu"
	echo "	-f plik_z_logiem	do jakiego pliku maj by logowane informacje"
	exit 1
}

args=`getopt dVf: $*`

if [ $? != 0 ]
then
	usage
	exit 1
fi

set -- $args

if [ "x$TRFFILE" != "x" ] ; then
	logfile=~/$TRFFILE
fi

for i
do
	case "$i"
	in
		-d)
			set -x
			shift;;
		-V)
			version
			exit 1
                        shift;;
		-f)
			logfile=~/$2; shift
			shift;;
                --)
                        shift; break;;
         esac
done

OS=`uname -s`
if [ "$OS" = "Linux" ]; then
	port=ttyS0 # port, ktrego uywa modem
	DATE="date +%c"

check_state() {
	# Metoda z lockiem sprawdzona na pppd, wvdial i kppp
	if [ -e /var/lock/LCK..${port} ]; then
		pstate=$state
		state=up
	else
		pstate=$state
		state=down
	fi
}

else
	DATE="date +%+"
	interface=tun0

check_state() {
	if [ -e /var/run/$interface.pid ]; then
		pstate=$state
		state=up
	else
		pstate=$state
		state=down
	fi
}

fi

export LC_ALL=C

if [ -e "$logfile".current ] ; then
        echo "Plik z logiem istnieje."
        exit 1
fi

while sleep 1; do
	check_state
	if [ "$state" = "up" ]; then
		if [ "$pstate" = "down" -o "x$start" = "x" ]; then
			start="`$DATE`"
		fi
		[ -e "$logfile.current" ] && cat $logfile.current > $logfile.current.bak
		sync
		echo -n "$start" > $logfile.current
		end="`$DATE`"
		echo " $end" >> $logfile.current
	fi
	if [ "$state" = "down" ]; then
		if [ "$pstate" = "up" ]; then
			echo -n "$start" >> $logfile
			end="`$DATE`"
			echo " $end" >> $logfile
			rm $logfile.current
			[ -e "$logfile.current.bak" ] && rm $logfile.current.bak
		fi
	fi
done
