#!/usr/bin/perl
use strict;
use warnings;
use HTTP::Tiny;
use Path::Class;
use autodie;
use Date::Calc qw(Today Day_of_Week Add_Delta_Days);

my $scribe = "";
my $currentPointer = 0;
my @scribelist;

system("cvs update scribe.list");

my ($dir, $file, $file_handle);
$dir = dir(".");
$file = $dir->file("scribe.list");
$file_handle = $file->openr();

while(my $name = $file_handle->getline() ) {
   push(@scribelist, $name);
}

for(my $i = 0 ; $i < @scribelist; $i++) {

  if($scribelist[$i] =~ m/^-->/) {
    $scribe = $scribelist[$i];
    chomp($scribe);
    $scribelist[$i] = "   $'";
    $currentPointer = $i;
  }
}

my $scribelistSize = @scribelist;

$currentPointer++;
if($currentPointer == $scribelistSize) {
  $currentPointer = 0;
}

$scribelist[$currentPointer] = "-->".substr($scribelist[$currentPointer], 3);

$file_handle = $file->openw();
for my $nameout (@scribelist) {
  $file_handle->print("$nameout");
}


## setup date stuff
my %monthName     =  qw (01   January
                         02   Febuary
                         03   March
                         04   April
                         05   May
                         06   June
                         07   July
                         08   August
                         09   September
                         10   October
                         11  November
                         12  December                  
                       );


sub leadingZero {
  # add leading zeros to numbers less than 10
  my $dateStr = shift(@_);
  if($dateStr !~ m/^[0-3][0-9]/) {
    $dateStr = "0".$dateStr;
  }
  return $dateStr;
}

my($year,$month,$day) = Today();
my $nextday = 3; # Wednesday
my $dow = Day_of_Week($year,$month,$day);

my $delta = (7 + $nextday - $dow) % 7;
my ($y,$m,$d) = Add_Delta_Days($year, $month, $day, $delta);

my $meetingDate = leadingZero($d) ."-". $monthName{leadingZero($m)} ."-". $y;

print("What is the date of the meeting? (ENTER for default of $y-$m-$d):");

chomp(my $userMeetingDate = <STDIN>);

if($userMeetingDate ne "") {
  ($y,$m,$d) = split(/-/, $userMeetingDate);
  $meetingDate = $userMeetingDate;
}

my $pdelta = -14; # 2 weeks between meetings
my ($py,$pm,$pd) = Add_Delta_Days($y, $m, $d, $pdelta);

my $draftMinutesUrl = "http://www.w3.org/2011/webappsec/draft-minutes/$py-".leadingZero($pm)."-".leadingZero($pd)."-webappsec-minutes.html";

## TODO: get count of open and overdue actions
#my $trackerUrl = "http://www.w3.org/2011/webappsec/track/";
#my $trackerResponse = HTTP::Tiny->new->get($trackerUrl);

my @topicList;

## start by pushing actions onto the topic list
my %actionsReview;
$actionsReview{'name'} = "Review of Open Actions in the Tracker";
$actionsReview{'link'} = "http://www.w3.org/2011/webappsec/track/actions/open?sort=owner";
push(@topicList, \%actionsReview);

## next GitHub issues
my %specIssues;;
$specIssues{'name'} = "Review of Spec Actions on GitHub";
$specIssues{'link'} = "https://github.com/w3c/webappsec/issues";
push(@topicList, \%specIssues);


sub getTopics {

my $y = $_[0];
my $m = $_[1];

my @topicList;

## get the recent mailing list archives by subject
my $archiveBase = "http://lists.w3.org/Archives/Public/public-webappsec/$y".substr($monthName{leadingZero($m)},0,3)."/";
my $archiveUrl = $archiveBase."subject.html";
my $archiveResponse = HTTP::Tiny->new->get($archiveUrl);
die "Failed to retrieve $archiveUrl\n" unless $archiveResponse->{success};
print "Retrieved " . length($archiveResponse->{content}) . " bytes of $archiveUrl\n\n\n";
my @content = split /\n/, $archiveResponse->{content}; 

my $line = 0;

while($line < @content && $content[$line] !~ m/"messages-list"/) { 
  $line++; 
}
$line++;

## now parse the current month's topics from the mailing list
while($line < @content && $content[$line] !~ m/id="end"/) { 

  my %currTopic;
  my $topicCount = 0;
  my $minutes = 0;

  while($line < @content && $content[$line] !~ m/dfn/) { 
    $line++; 
  }
  if($line == @content) { last; }
  if($content[$line] =~ m/id="end"/) { last; }

  if($content[$line] =~ m/<dfn>(.+)<\/dfn>/) { 
    $currTopic{'name'} = $1;
    $line+=2;
    $content[$line] =~ m/href="([\d\w\.]*)"/;
    $currTopic{'link'} = $archiveBase.$1;
 }
  
  while($line < @content && $content[$line] =~ m/^<li>/) { 
    $topicCount++;
    $line++; 
  }

  $currTopic{'count'} = $topicCount; 
  push(@topicList, \%currTopic); 

  $topicCount = 0;

  $line++;
}

return @topicList;
## end getting topics from archive
}


# get current month's list topics
my @archiveTopics = &getTopics($y,$m);

foreach(@archiveTopics) {
  push(@topicList, $_);
}

# get prior month's list topics if last meeting was in prior month
if($pm != $m) {
 my @pArchiveTopics = &getTopics($py,$pm);

 foreach(@pArchiveTopics) {
  push(@topicList, $_);
 }
}





my $minutesRemaining = 52;
for(my $i = 0 ; $i < @topicList; $i++) {
  
  print("\n");
  if($topicList[$i]{'count'}){
    print("TOPIC: $topicList[$i]{'name'} ($topicList[$i]{'count'} messages in thread.)\n");
  } else {
    print("TOPIC: $topicList[$i]{'name'} \n");
  }
  print("$topicList[$i]{'link'}\n");
  print("Minutes to devote ($minutesRemaining remaining): ");

  chomp($topicList[$i]{'minutes'} = <STDIN>);

  $minutesRemaining -= $topicList[$i]{'minutes'};
}
	
if($minutesRemaining > 0) {
  my %aob;
  $aob{'name'} = "AOB";
  $aob{'minutes'} = $minutesRemaining;
  $aob{'link'} = "";
  push(@topicList, \%aob);
}


## print out the agenda
print("\n\n###############################################################################\n\n");
print("WebAppSec WG Teleconference $meetingDate  08:00 PDT\n");
print("+1.617.761.6200; PIN 92794 ('WASWG') and  #webappsec on irc.w3.org:6665\n");
print("(Or VoIP via the Zakim SIP bridge: http://www.w3.org/2006/tools/wiki/Zakim-SIP)\n");
print("\n"); 
print("08:00 - 08:03    Scribe Selection (Default $scribe)\n");
print("08:03 - 08:05    Roll Call\n");
print("08:05 - 08:06    Minutes Approval\n");
print("    $draftMinutesUrl \n\n");
print("08:06 - 08:08    Agenda Bashing\n"); 

my $currMinute = 8;

for my $hashref (@topicList) {
  my %hash = %{$hashref};

  if($hash{'minutes'} != 0) {
    my $startMinute = leadingZero($currMinute);
    my $endMinute = leadingZero($currMinute + $hash{'minutes'});
    if($endMinute == 60)
    {
      print("08:$startMinute - 09:00");
    }  else {
      print("08:$startMinute - 08:$endMinute");
    }
    $currMinute += $hash{'minutes'};
    print ("    TOPIC: $hash{'name'}\n");
    print ("    $hash{'link'}\n\n");
  }
}
print("Scribe list for upcoming meetings:\n");
print("(Arrow indicates NEXT scribe)\n");
print("----------------------------------\n");
print(@scribelist);

print("\n\n###############################################################################\n\n");

print("don't forget to \"cvs commit -m 'updated scribe list' scribe.list\"\n");
