#!/usr/athena/bin/perl
# Door sensor script
# blame <ternus@mit.edu>

use Device::ParallelPort;
use Device::ParallelPort::drv::linux;
use Getopt::Long;
use Time::Duration;

use warnings;
use strict;

my $port = Device::ParallelPort->new();
my $bit = 13;
my @states = ("closed", "open");
my $logfile = "/afs/sipb/project/door/log";
my $logbackup = "/tmp/doorsensor_bk";
my $curstate = -1;
my $lasttime = time();

GetOptions(	"logfile|log|l|f=s" => \$logfile,
				"backup|b=s" => \$logbackup,
				"bit=i" => \$bit);

chdir("/tmp");

$ENV{"KRB5CCNAME"} = "/tmp/krb5cc_door";
$ENV{"KRBTKFILE"} = "/tmp/tkt_door";

system("/usr/athena/bin/kinit -45 -k -t /etc/krb5.keytab");
system("/bin/athena/aklog sipb");

sub bail {
	my $error = shift;
	my $msg = shift;
	system("/usr/athena/bin/zwrite -c sipb-door -i error -m \"Error: $error\n$msg\"");
	system("/bin/athena/unlog");
	system("/usr/athena/bin/kdestroy");
	
	die "$error : $msg";
}

if (-e $logfile) {
	open(LOGFILE, "<$logfile") or bail("Can't open logfile", $!);
	my @lines = <LOGFILE>;
	my $line = pop(@lines);
	($curstate, $lasttime) = split(/,/,$line);
	close(LOGFILE);
}
else {
	open(LOGFILE, ">$logfile") or bail("Can't create logfile $logfile", $!); 
	print LOGFILE 	"# Logfile for the SIPB door sensor\n" .
						"# <sipb-door\@mit.edu>\n" .
						"# Format:\n" .
						"# new state, current time, human-readable new state, human-readable time, time spent in previous state\n";
	close(LOGFILE);
}

my $portval = $port->get_bit($bit); # or bail("Error accessing parallel port", $!);

print "$curstate  $portval \n";	
if ($curstate ne $portval) {
	open(LOGFILE, ">>$logfile") or bail("Can't open logfile", $!);
	open(LOGBACKUP, ">>$logbackup") or bail("Can't open logfile", $!);
	$curstate = $portval;
	my $out = $curstate . "," . time . "," . $states[$curstate] . "," . localtime() . "," . duration(time() - $lasttime) . "\n";
	print LOGFILE $out;
	print LOGBACKUP $out;
	close(LOGFILE) or bail("Error in closing $logfile", $!);
	close(LOGBACKUP) or bail("Error in closing $logfile", $!);
	
	system("/usr/athena/bin/zwrite -c sipb-auto -i door -m \"The door is now $states[$curstate].\"");
	system("/usr/athena/bin/zwrite -c sipb-door -i $states[$curstate] -m \"The door is now $states[$curstate].\"");
	system("/bin/athena/unlog");
	system("/usr/athena/bin/kdestroy");
}
