#!/usr/bin/perl

# ToledoForum v1.6b
# Copyright (C) 2005 Davy Preuveneers <davy.preuveneers AT cs.kuleuven.be>
# 
# ToledoForum is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# ToledoForum is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


use strict;
use WWW::Mechanize;
use HTML::TokeParser;
use HTTP::Cookies;

use Socket;

#This is your m-number, s-number or u-number
my $user = ''; 
#This is your password
my $password = ''; 
#This is a list of course IDs you would like to monitor, see below for course id's
my @courseid = ();

#Adjust where necessary
my $mailto = '';
my $mailserver = 'mail.cs.kuleuven.be';

my $agent = WWW::Mechanize->new( autocheck => 1 );
my %courses = ( '_21737_1', 'Informatica-Werktuigen', 
                '_18250_1', 'Gedistribueerde systemen en computernetwerken',
                '_18247_1', 'Methodologieen voor Ontwikkeling van Programmatuur');

my $flag = 0;

# example config file:
# user=u0012658
# password=youwish
# mailto=Firstname.Lastname AT cs.kuleuven.be
# mailserver=mail.cs.kuleuven.be
# courseid=_18576_1
# courseid=_47015_1
# coursedesc=_18576_1:Internet Infrastructuur
# coursedesc=_47015_1:Computer Netwerken en Gedistribueerde Systemen
sub parseConfigFile {
  open (CONFIG,"$ENV{HOME}/.ToledoForum") or return;
  my $line = '';
  my $key = '';
  my $value = '';
  my $counter = 0;

  while ($line = <CONFIG>) {
    chop($line);
    ($key,$value)=split(/=/,$line);
    if ($key eq "user") {
      $user = $value;
    }
    if ($key eq "password") {
      $password = $value;
    }
    if ($key eq "mailto") {
      $mailto = $value;
    }
    if ($key eq "mailserver") {
      $mailserver = $value;
    }
    if ($key eq "courseid") {
      $courseid[$counter] = $value;
      $counter++;
    }
    if ($key eq "coursedesc") {
       my($id,$desc)=split(/:/,$value);
       $courses{$id}=$desc;
    }
  }
  close(CONFIG);
}

sub parseCommandLine {
  if ($ARGV[0]) {
    $user = $ARGV[0];
  }
  if ($ARGV[1]) {
    $password = $ARGV[1];
  }
  if ($ARGV[2]) {
    $courseid[0] = $ARGV[2];
  }
  if ($ARGV[3]) {
    $mailto = $ARGV[3];
  }
  if ($ARGV[4]) {
    $mailserver = $ARGV[4];
  }
}

sub promptUserID {
  print("User ID: ");
  $| = 1;
  $_ = <STDIN>;
  chomp; 
  return $_;
}  

sub promptPassword {
  print("Password: ");
  $| = 1;
  
  if (-e '/bin/stty' || -e '/usr/bin/stty' || -e '/usr/local/bin/stty') {
    `stty -echo`;
    $_ = <STDIN>;
    `stty echo`;
    print "\n";
  } else {
    $_ = <STDIN>;
  }  
  chomp; 
  return $_;
}

sub promptCourseID {
  my(@keys) = keys(%courses);
  my($k);
  foreach $k (@keys) {
    print("  $k     $courses{$k} \n");
  } 
  print("Course ID: ");
  $| = 1;
  $_ = <STDIN>;
  chomp; 
  return $_;
}

sub parseUserInput {
  if ($user eq "") {
    $user = &promptUserID();
  }
  if ($password eq "") {
    $password = &promptPassword();
  }
  if ($courseid[0] eq "") {
    $courseid[0] = &promptCourseID();
  }
}

sub ToledoLogin {
  $agent->cookie_jar(HTTP::Cookies->new);
               
  $agent->get("https://cygnus.cc.kuleuven.ac.be/webapps/portal/tab/_107_1/index.jsp");
  
  $agent->follow_link( url_regex => qr/login/i, n => 1 );
  $agent->follow_link( url_regex => qr/https:\/\/cygnus.cc.kuleuven.ac.be/i, n => 1 );
  $agent->follow_link( url_regex => qr/login/i, n => 1 );
  $agent->follow_link( url_regex => qr/https:\/\/cygnus.cc.kuleuven.ac.be/i, n => 1 );

  $agent->form(1);
  $agent->field("user_id", $user);
  $agent->field("password", $password);
  $agent->field("config", "a");

  $agent->click();
  $agent->follow_link( url_regex => qr/https:\/\/cygnus.cc.kuleuven.ac.be/i, n => 1 );
}

sub sendSMTP {
  my($buffer) = @_;
  send(SMTP, $buffer, 0);
  recv(SMTP, $buffer, 200, 0);
}

sub sendMail {
  my($body) = $_[0];
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime time;
  my $subject = 'Toledo Discussion Board Overview (' . (1900+$year).'-'.(1+$mon).'-'.($mday).')';
  my $mailfrom = $mailto;
  
  socket(SMTP, AF_INET(), SOCK_STREAM(), 6);
  
  connect(SMTP, pack('S n a4 x8', AF_INET(), 25, (gethostbyname($mailserver))[4]));    
  my($buffer);
  recv(SMTP, $buffer, 200, 0);
    
  sendSMTP("HELO localhost\n");
  sendSMTP("MAIL From: <$mailfrom>\n");
  sendSMTP("RCPT To: <$mailto>\n");
  sendSMTP("DATA\n");

  send(SMTP, "From: $mailfrom\n", 0);
  send(SMTP, "To: $mailto\n", 0);
  send(SMTP, "Subject: $subject\n", 0);
  send(SMTP, $body, 0);

  sendSMTP("\r\n.\r\n");
  sendSMTP("QUIT\n");
  close(SMTP);
}

sub getForum {
  my($id) = $_[0];
  
  $agent->get( "https://cygnus.cc.kuleuven.ac.be/webapps/blackboard/content/courseMenu.jsp?course_id=>$id&mini=>Y" );
  $agent->follow_link( url_regex => qr/family=communication/i, n => 1 );
  $agent->follow_link( url_regex => qr/nav=discussion_board/i, n => 1 );
  $agent->follow_link( text => "Communication");
  $agent->follow_link( text => "Discussion Board");

  my($message) = "$courses{$id}:\n";
  my($l) = length($message);
  
  my($i);
  for ($i = 1; $i<$l; $i++) {
    $message = $message . "-";
  }
  $message = $message . "\n";
  my @lines = split(/\n/, $agent->{content});
  foreach my $line (@lines) {
    chop($line);
    if ($line =~ /<strong>(.*)<\/strong>.*Number of Messages: ([0-9]+)<br>\[&nbsp;([0-9]+)&nbsp;/) { 
       $message = $message . "  $1: ";
       for ($i = length($1); $i<30; $i++) {
         $message = $message . " ";
       }       
       $message = $message . "$2 Messages, $3 New\n";
       $flag = 1;
    } elsif ($line =~ /<strong>(.*)<\/strong>.*Number of Messages: ([0-9]+)<br>\[&nbsp;All&nbsp;/) { 
       $message = $message . "  $1: ";
       for ($i = length($1); $i<30; $i++) {
         $message = $message . " ";
       }       
       $message = $message . "$2 Messages, All New\n";
       $flag = 1;       
    } elsif ($line =~ /<strong>(.*)<\/strong>.*Number of Messages: ([0-9]+)<br>(.*)<\/font>/) { 
       $message = $message . "  $1: ";
       for ($i = length($1); $i<30; $i++) {
         $message = $message . " ";
       }       
       $message = $message . "$2 Messages, $3\n";
    }
  }
  $message = $message . "\n"; 
  return $message;
}

sub getOverview {
  my $overview = "\n"; 
  $flag = 0;
  
  my $c;
  foreach $c (@courseid) {
    $overview = $overview . getForum($c);  
  }
  return $overview;
}

&parseConfigFile();
&parseCommandLine();
&parseUserInput();
&ToledoLogin();

my $mail = &getOverview();
print $mail;

if ($mailto && $flag) {
  print "Sending mail to $mailto ...\n";
  sendMail($mail);
}

