use Apache;
use Apache::Cookie;
use Apache::Constants qw(:response :common);
use Data::Dumper;

my $cookiename = "TicketDestination";

my $r = Apache->request();
my $self = $r->uri;
my $is_https = ($ENV{HTTPS} eq 'on');
my $have_prev = defined $r->prev;
my $destination = '';
my $refreshto = '';
my $returnto = '/';
my $pathinfo = $r->path_info;
my %cookies = Apache::Cookie->fetch;
my $have_cookie = defined $cookies{$cookiename};
my $have_user = defined $r->connection->user;

my $ie_friendly_error_override = ' 'x512;

if ($have_prev)
   {
   $returnto = $r->prev->uri;
   my $args = $r->prev->args;
   $returnto .= "?$args" if length($args);
   }
elsif (length($pathinfo))
   {
   $returnto = $pathinfo;
   }

my $cookie = Apache::Cookie->new($r,
   -name=>$cookiename,
   -expires=>'0',
   -value=>$returnto,
   -path=>'/',
   );

if ($is_https)
   {
   if ($have_cookie)
      {
      if ($have_user)
         {
         $refreshto = $cookies{$cookiename}->value.":NOSSL";
         $cookie->expires('-1y');
         $cookie->bake;
         }
      else { $destination = $r->uri; }
      }
   else { $destination = $returnto; }
   }
else
   {
   $refreshto = $r->uri().":SSL";
   $cookie->expires('+60s');
   $cookie->bake;
   }

$r->content_type('text/html');
$r->send_http_header;

if (length($refreshto))
   {
   $r->print( <<EOF );
<html>
<head><meta http-equiv="refresh" content="0;url=$refreshto"></head>
<body>$ie_friendly_error_override</body>
</html>
EOF

   return;
   }

if (length($destination))
   {
   $r->print( <<EOF );
<head>
<meta http-equiv="expires" content="-1">
<title>log in</title>
</head>
<body bgcolor="#ffffff" onload="document.forms[0].credential_0.focus();">
<div align=center><table height="85%"><tr><td valign=center>
<h1>Please log in:</h1>
<form method="POST" action="/LOGIN">
<input type="hidden" name="destination" value="$destination">
<table>
<tr><td>Username</td><td><input type="text" name="credential_0"></td></tr>
<tr><td>Password</td><td><input type="password" name="credential_1"></td></tr>
</table>
<input type="submit" value="Log In">
</form>
<em>Note:</em><br>
Set your browser to accept cookies in order for login to succeed.<br>
You will be asked to log in again after some period of time.<br>
$ie_friendly_error_override
</td></tr></table></div>
<html>
EOF

   return;
   }
