#!/usr/bin/perl

use Time::Local;
use POSIX;

$ENV{TZ} = 'Europe/London';
POSIX::tzset();

$canonical_host = 'mcios.pathetech.com';
$scheme = $ENV{'HTTPS'} ? "https" : "http";

$method = $ENV{'REQUEST_METHOD'};
$script = $ENV{'SCRIPT_NAME'};
$query = $ENV{'QUERY_STRING'};
$referer = $ENV{'HTTP_REFERER'};
$host = $ENV{'HTTP_HOST'};

$stateLocked = "L";
$stateInvisible = "I";
$stateActive = "A";
$stateArchived = "R";

&setPairs( $query);

$document_root = ".";
$game_root = "/site/mornington";
$image_dir = $document_root . "/images/";
$game_dir = $game_root . "/games/";
$hits_dir = $game_dir;
$hits_file = "LastSearchTerms.txt";
$main_script = "./";
$move_script = "move.pl";
$shared_lock = 1;
$exclusive_lock = 2;
$unlock = 8;

$active_limit = 12;

$hdr_canonical = $ENV{'HTTP_HOST'} =~ /$canonical_host/ ? '' : "Link: <$scheme://$canonical_host/morgue.pl>; rel=\"canonical\"\n";
$meta_canonical = "<link rel='canonical' href='$scheme://$canonical_host/morgue.pl' />\n";
#$meta_canonical = $host =~ /$canonical_host/ ? "" : "<link rel='canonical' href='$scheme://$canonical_host/morgue.pl' />\n";
$meta_robots = '<meta name="robots" content="noindex,nofollow">';

#some HTML body values

$body_bgcolor = "#ECECEC";
$body_background = "bg_stc.gif";
$body_text = "#000000";
$body_link = "#0000FF";
$body_alink="#FF2020";
$body_vlink = "#800020";

#some file values
$game_literal = "Game_";
$game_ext = ".txt";
$game_num = $query;
$full_path = $game_dir . "ActiveGames" . $game_ext;

@days = qw( Sun Mon Tue Wed Thu Fri Sat Sun);
@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);

&showGames();

exit( 0);

sub showGames {

  print <<End_content_header;
Content-type: text/html; charset=UTF-8
${hdr_canonical}Pragma: no-cache
X-UA-Compatible: IE=edge
Cache-control: no-cache
End_content_Header

<!DOCTYPE html>
<html>
<head>
$meta_robots
<meta name="Keywords" content="Mornington Crescent, Mornington, ISIHAC, Cress, Cheddar Gorge, Limericks">
<meta name="Generator" content="Ultimate Crescent Server II: $script (Perl5)">
<meta name="viewport" content="width=device-width, minimum-scale=1.0">
$meta_canonical
<link rel='stylesheet' type='text/css' href='scripts/mchomez.css' />
<script src='scripts/mcmorgue.js'></script>

<title>
Mortuary Crescent &aacute; Go Go
</title>
</head>

<body>

<h2 style='text-align: center;'>
The Mornington Crescent Archive
</h2>
<p>
<hr>
<p>
End_content_header

  open ( GAMEFILE, "<" . $full_path)
    || die "Could not open requested game file $full_path\n";
  flock ( GAMEFILE, $shared_lock);

  $game_count = 0;
  $active_count = 0;
  $archived_count = 0;
  while ( $user_line = <GAMEFILE>) {
    $user_line =~ s/[\n\r]//eg;
    if ( $user_line) {
      chomp $user_line;
      # $user_line =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
      ($game_number, $game_name, $game_state, $winning_move, $last_user, $last_dayTime) =
          split( /~/, $user_line);
      $game_count++;
            if (( $game_state eq $stateArchived) || ( $game_state eq $stateLocked)) {
              $archived_game[$archived_count++] = $user_line;
      }

    }
  }

  flock (GAMEFILE, $unlock);
  close(GAMEFILE);

  print STDOUT "<div class='plain_term'><img src='images/grn_top_term.gif'></div>\n"; 
  
  if ( $archived_count > 0) {

print STDOUT <<End_this_header;
<div class='leftimg'><img src='images/grn_vert.gif'></div>
<div class='listhdr'>List of Finished Games:</div>
<div class='clearfix'></div>
<div class='game furn'>
  <div class='limpid_left'><a href='#' id='sort_game'>sort by game</a></div>
  <div class='limpid_right'> <a href='#' id='sort_lmtime'>sort by last played</a></div>
<div class='clearfix'></div>
</div>
End_this_header
    for ( $i = 0; $i < $archived_count; $i++) {
      &printGameRow($archived_game[$i]);
    }
        
    print STDOUT "<div class='plain_term' id='toe_tag'><img src='images/grn_bot_term.gif'></div>\n";
    
  }

print <<End_content_footer;

<div class='noticeblock'>
Old games are resurrected, zombie-<WBR>like, when you inflate their foul, decayed lungs by
adding a move or comment to them.  This causes a debased glimmer of their former
intelligence to flicker briefly in their rotted brains, and they lurch onto the
recently-<WBR>updated list for a few days.
<br><br>
If the very idea makes you gag, you can always <A href="${main_script}" title="Chicken">return</a> to the clean,
well-<WBR>lit, formaldehyde-<WBR>free climes of the main page.
</div>
</body>
</html>
End_content_footer

}

sub printGameRow {

  local $game_url, $game_label, $game_number, $game_name, $game_state, $winning_move,
        $last_user, $last_dayTime, $state_cls, $time_string, $lmTime;

  # print STDOUT "<!-- $_[0] -->\n";
  ($game_number, $game_name, $game_state, $winning_move, $last_user, $last_dayTime) =
      split( /~/, $_[0]);

  $state_cls = 'archived';
  
  foreach $v (\$game_name,\$winning_move,\$last_user,\$last_dayTime) {
      $$v =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
  }

        if ( $last_dayTime ne '') {
            $time_string = &cvtTime( $last_dayTime);
            $lmTime = &sortTime( $last_dayTime);
        }
                                         
  $game_url = "${move_script}?" . $game_number;

  if ( $game_number =~ m/(\d+)/) {
      $game_label = "Game " . $game_number;
  } else {
      $game_label = $game_number;
  }
  print STDOUT "<div class='game $state_cls' lmtime='$lmTime' gamenumber='$game_number'>\n",
              "\t<div class='gameid'><a href='$game_url' title='Most recent activity in $game_label'>$game_label</a>:</div>\n",
        "\t<div class='info'>\n\t\t<div class='title'>$game_name</div>\n";
  if ( $last_user ne "") {
      print STDOUT "\t\t<div class='played'>($last_user: $time_string)</div>\n";
  }

  print STDOUT "\t</div>\n<div class='clearfix'></div>\n</div>\n";

}

sub cvtTime {
    $time_in = $_[ 0];

    ( $wday, $yday, $day, $nmonth, $year, $hour, $min, $sec) =
        split ( /-/, $time_in);

     $dow = $days[ $wday];
     $mon = $months[ $nmonth];

     return sprintf "%s, %02d %s %4d %02d:%02d", $dow, $day, $mon, $year+1900, $hour, $min;
}

sub sortTime {                                                                                  
    $time_in = $_[ 0];                                                                          
    local( $wday, $yday, $day, $nmonth, $year, $hour, $min, $sec) =                             
        split ( /-/, $time_in);                                                                 
    return sprintf "%d", timegm( $sec, $min, $hour, $day, $nmonth, $year);                      
}                                                                                               
                                                                                                

sub setPairs {
    $value_in = $_[ 0];
    @ary = split ( /\&/, $value_in);

    foreach $pair ( @ary)
    {
        ($n, $v) = split ( /=/, $pair);
        if ( $n == 0)
        {
            $$n = $v;
        }
    }

}


