#!/usr/local/bin/perl -T
use strict;
use lib '/dept/phys/software/Perl5/lib';
use lib '/dept/phys/software/Perl5/lib/site_perl';
use lib '/group/pcs/software/FakeCAS';
use PNCE::FakeCAS;
use Template;

#Setting this will force debug regardless of ticket
my $DEBUG=0;
$DEBUG=1;

my $template_config = 
{  	POST_CHOMP => 1,
	INCLUDE_PATH => [@INC],
	COMPILE_DIR => "/tmp/compile-dir.$<",
	PROCESS => ['WRAPPER.tt'],
};

my $fakecas = new PNCE::FakeCAS;
my $cgi = $fakecas->cgi;
my $service = $cgi->param('url');

my $debug=0;

sub debug(@)
{	my @args = @_;
	if ($debug || $DEBUG)
	{	my $now = localtime;
		my $header = "$now FakeCAS-debug:";
		my $str = join '', @args;
		warn("$header $str\n");
	}
}

sub display_template($;$)
#Displays named template, passing the vars in $vars.  The var fakecas=>$fakecas
#will be added to the var list unless fakecas key present.
{	my $template = shift;
	my $vars = shift || {};
	$vars->{fakecas} = $fakecas unless exists $vars->{fakecas};

	my $ttobj = new Template $template_config;
	my $res = $ttobj->process($template,$vars);
	unless ( $res )
	{	warn("Error processing template: " .  $ttobj->error);
	}

	exit 0;
}

#See if we have a TGT
my $ip = $ENV{REMOTE_ADDR};
my $tgt = $fakecas->get_cookie;
my ($username, $flags) = $fakecas->parse_tgt($tgt);
if ( $username && $fakecas->valid_username($username) && $flags 
	&& ref($flags) eq 'HASH' )
{	#Valid TGT
	$debug = $flags->{debug} || 0;
	debug("logout called by user $username\@$ip, clearing TGT $tgt");
} else
{	debug("logout called from $ip, but no TGT to clear");
}
debug("url is $service");

display_template('logout.tt',
	{ 	username=>$username, 
		tgt=>'*DELETE*',
		url=>$service,
	}
	);
die "Should not reach here";
