New options system (messy)
[tpope-extra.git] / perl / schedproc
1 #!/usr/bin/perl -w
2 # $Id$
3 # -*- perl -*- vim: ft=perl sw=4 sts=4
4
5 # Brief usage instructions:
6 # Create a ~/.schedprocrc that has schedule=/path/to/schedule.xml and
7 # grades=/path/to/grades.xml.  HTTP URLs are acceptable
8
9 use strict;
10 use Date::Calc::Object qw(Day_of_Week Decode_Day_of_Week Decode_Month Week_of_Year Monday_of_Week Day_of_Week_Abbreviation Delta_Days Add_Delta_Days Nth_Weekday_of_Month_Year Gmtime Mktime);
11 use Date::Calendar::Profiles qw($Profiles);
12 use Date::Calendar::Year;
13 use Getopt::Long;
14 use LWP::UserAgent;
15 use XML::Simple;
16 use vars qw(%opts %faculty);
17
18 $opts{'config'} = $ENV{HOME} . "/.schedprocrc";
19
20 if(($ARGV[0] || "") eq '-F') {
21     shift;
22     $opts{'config'} = shift;
23 }
24
25 my $arg = $ARGV[0] || "";
26 if($arg eq "-x") {
27     shift;
28     $opts{'format'} = "xml";
29 } elsif($arg eq "-h") {
30     shift;
31     $opts{'format'} = "html";
32 } elsif($arg eq "-m") {
33     shift;
34     $opts{'format'} = "mhc";
35 } elsif($arg eq "-c") {
36     shift;
37     $opts{'format'} = "csv";
38 } elsif($arg eq "-v") {
39     shift;
40     $opts{'format'} = "vcs";
41 } elsif($arg eq "-g") {
42     shift;
43     $opts{'format'} = "grades";
44 }
45
46 Getopt::Long::Configure ("bundling", "auto_help");
47 die "Invalid arguments\n" unless
48 GetOptions(\%opts, 'schedule=s', 'grades=s', 'name=s', 'format|f=s', 'config|F=s', 'out|o=s');
49
50 if (-r $opts{'config'}) {
51     open CONFIG, $opts{'config'};
52     while(<CONFIG>) {
53         s/\#.*//;
54         next unless m/^([^=]*)=(.*)/;
55         my ($l, $r) = ($1, $2);
56         if ($l =~ /^(schedule|grades|name)$/) {
57             $opts{$l}||=$r;
58         } else {
59             warn "Unknown config file option $l.\n";
60         }
61     }
62     close CONFIG;
63 }
64
65 $opts{'schedule'} ||= "~/schedule.xml";
66 $opts{'grades'} ||= "~/grades.xml";
67
68 $opts{'schedule'} =~ s/^~\//$ENV{HOME}\//;
69 $opts{'grades'} =~ s/^~\//$ENV{HOME}\//;
70
71 if(!defined($opts{'out'}) && defined($ARGV[0])) {
72     $opts{'out'} = shift;
73 }
74
75 if(!defined($opts{'format'}) && defined($opts{'out'})) {
76     $opts{'format'} = $opts{'out'};
77     $opts{'format'} =~ s/.*\.//;
78     $opts{'format'} =~ s/^(.*\/|)\.?schedule$/mhc/;
79     undef $opts{'out'} if($opts{'out'} =~ /^(html|mhc|csv|cvs|xml|grades)$/);
80 }
81
82 $opts{'format'} ||= "";
83 undef $opts{'out'} if(($opts{'out'}||"") eq "-");
84
85 sub generate_id {
86     my ($section, $number) = split("-", shift);
87     my $id = 0;
88     foreach (split //, $section) {$id=26*$id+(ord($_)-1)%32;}
89     $id=10000*$id+$number;
90     return $id;
91 }
92
93 sub next_class {
94     my %class = @_;
95     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
96     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
97     my $firstday = Date::Calc->new($1,$2,$3);
98     my $lastday = Date::Calc->new($4,$5,$6);
99     my $today = Date::Calc->new(Date::Calc->localtime(time+3600*6)->date);
100     my @days=();
101     foreach(split(" ",$class{'days'})) {
102         push @days, Decode_Day_of_Week($_);
103     }
104     my @off = ();
105     @off = @{$class{'off'}} if ($class{'off'});
106     for($today = ($today > $firstday ? $today : $firstday); $today < $lastday; $today++) {
107         next unless(grep($_ == Day_of_Week($today->date), @days));
108         next if(grep($_ == "$today", @off));
109         return $today;
110     }
111     $today = Date::Calc->new(Date::Calc->gmtime->date);
112     for($today = ($today < $lastday ? $today : $lastday); $today > $firstday; $today--) {
113         next unless(grep($_ == Day_of_Week($today->date), @days));
114         next if(grep($_ == "$today", @off));
115         return $today;
116     }
117     return undef;
118 }
119
120 sub capitalize {
121     local $_ = shift || "";
122     s/ +$//;
123     s/\b([A-Z])([A-Z]*)\b/$1\L$2/g;
124     s/\b(I)(i*)\b/$1\U$2/g;
125     s/\bUs\b/US/g;
126     s/ (And|For|Of|Or|The|To|With) / \l$1 /g;
127     s/\b(Mc)([a-z])/$1\u$2/g;
128     s/\b(Tcp\/Ip|Pc|Tba)\b/\U$&/g;
129     s/\bThru\b/Through/g;
130     s/\bAcct\b/Accounting/g;
131     s/\bAmer\b/American/g;
132     s/\bChem\b/Chemistry/g;
133     s/\bComp\b/Composition/g;
134     s/\bFed\b/Federal/g;
135     s/\bGen\b/General/g;
136     s/\bIntro\b/Introduction/g;
137     s/\bPrgm\b/Programming/g;
138     s/\bOp Sys\b/Operating System/g;
139     #s/\bGovt\b/Government/g;
140     s/\bLit\b/Literature/g;
141     s/\bPrin\b/Principles/g;
142     s/\bBus\b/Business/g;
143     s/\bSyst\b/Sys/g;
144     return $_;
145 }
146
147 sub read_fileurl {
148     my $content;
149     my $url=shift;
150     if($url =~ /:\/\//) {
151         my $ua = LWP::UserAgent->new;
152         $ua->timeout(10);
153         $ua->env_proxy;
154 #       $ua->cookie_jar( {} );
155         my $response = $ua->get("$url") or die "$!";
156         die $response->status_line unless $response->is_success;
157         $content = $response->content;
158     } else {
159         open(F,$url) || die "$!";
160         $content = join ("", <F>);
161         close F;
162     }
163     return $content;
164     #my $ref = XMLin($content, ForceArray => [ 'class', 'cumulative', 'off' ], KeyAttr => "");
165     #return @{$ref->{'class'}};
166 }
167
168 sub get_schedule {
169     my $content = read_fileurl($opts{'schedule'});
170     my $ref = XMLin($content, ForceArray => [ 'class', 'off' ], KeyAttr => "");
171     return @{$ref->{'class'}};
172 }
173
174 sub get_grades {
175     my $content = read_fileurl($opts{'grades'});
176     my $ref = XMLin($content, ForceArray => [ 'class', 'cumulative' ], KeyAttr => "");
177     return $ref;
178 }
179
180 sub get_faculty_email {
181     my ($name, $school, $email);
182     if((-f $ENV{'HOME'} . "/public_html/faculty.csv") && ! %faculty) {
183         open INS, $ENV{'HOME'} . "/public_html/faculty.csv";
184         while($_ = <INS>) {
185             chomp;
186             m/"([^"]*)",([^,]*),([^,]*)/; # "
187             ($name, $email, $school) = ($1, $2, $3);
188             $name =~ s/ [A-Z]\.//g;
189             $name = lc $name;
190             $name =~ s/\W//g;
191             $faculty{$name} = $email;
192         }
193     }
194     $name = shift;
195     $name =~ s/ [A-Z]r?\.//g;
196     $name = lc $name;
197     $name =~ s/\W//g;
198     return $faculty{$name};
199 }
200
201 sub get_mhc_header {
202 return (
203 "X-SC-Subject: New Years Day\nX-SC-Category: Holiday\nX-SC-Cond: 1 Jan\nX-SC-Duration: 00010101-\nX-SC-Record-Id: <New_Years_Day\@from.sctweb>\n",
204 "X-SC-Subject: Martin Luther King, Jr. Day\nX-SC-Category: Holiday\nX-SC-Cond: 3rd Mon Jan\nX-SC-Duration: 19870119-\nX-SC-Record-Id: <Martin_Luther_King_Jr_Day\@from.sctweb>\n",
205 "X-SC-Subject: Presidents Day\nX-SC-Category: Holiday\nX-SC-Cond: 3rd Mon Feb\nX-SC-Duration: 19710515-\nX-SC-Record-Id: <Presidents_Day\@from.sctweb>\n",
206 "X-SC-Subject: Memorial Day\nX-SC-Category: Holiday\nX-SC-Cond: Last Mon May\nX-SC-Duration: 19710531-\nX-SC-Record-Id: <Memorial_Day\@from.sctweb>\n",
207 "X-SC-Subject: Independence Day\nX-SC-Category: Holiday\nX-SC-Cond: 4 Jul\nX-SC-Duration: 17760704-\nX-SC-Record-Id: <Independence_Day\@from.sctweb>\n",
208 "X-SC-Subject: Labor Day\nX-SC-Category: Holiday\nX-SC-Cond: 1st Mon Sep\nX-SC-Duration: 18840901-\nX-SC-Record-Id: <Labor_Day\@from.sctweb>\n",
209 "X-SC-Subject: Columbus Day\nX-SC-Category: Holiday\nX-SC-Cond: 2nd Mon Oct\nX-SC-Duration: 19711011-\nX-SC-Record-Id: <Columbus_Day\@from.sctweb>\n",
210 "X-SC-Subject: Veterans Day\nX-SC-Category: Holiday\nX-SC-Cond: 11 Nov\nX-SC-Duration: 19261111-\nX-SC-Record-Id: <Veterans_Day\@from.sctweb>\n",
211 "X-SC-Subject: Thanksgiving\nX-SC-Category: Holiday\nX-SC-Cond: 4th Thu Nov\nX-SC-Duration: 14921122-\nX-SC-Record-Id: <Thanksgiving\@from.sctweb>\n",
212 "X-SC-Subject: Christmas\nX-SC-Category: Holiday\nX-SC-Cond: 25 Dec\nX-SC-Duration: 00011225-\nX-SC-Record-Id: <Christmas\@from.sctweb>\n",
213 );
214 }
215
216 sub do_mhc_schedule {
217     $| = 1;
218     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
219     my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
220     my ($file, $current, @mhc, @schedule);
221     $file = $opts{'out'};
222     @schedule = get_schedule(@_);
223     @mhc = get_mhc_header;
224     if(defined($file) && (-d $file)) {
225         my @mhc2;
226         foreach (@mhc) {
227             $_ =~ s/X-SC-Subject: ([^\n]*)/X-SC-Subject: $1\nSubject: $1/;
228             $_ =~ s/X-SC-Category: ([^\n]*)/X-SC-Category: $1\nFrom: $1/;
229             $_ =~ s/X-SC-Duration: (\d\d\d\d)(\d\d)(\d\d)-/"X-SC-Duration: $1$2$3-\nDate: $3 " . $mon[$2-1] . " 1970 12:00:00 +0000"/e;
230             push @mhc2, $_;
231         }
232         @mhc = @mhc2;
233     }
234     foreach my $row (@schedule) {
235         map {s/\n/-/g if defined; $_} %$row;
236         my $id=generate_id($row->{'id'});
237         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
238         $row->{'days'} =~ s/^ //;
239         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
240         my @day = ();
241         @day = map { "!" . $_ } (@{$row->{'off'}}) if ($row->{'off'});
242         $current = "";
243         #print "# $id\n";
244         $current .= "X-SC-Subject: " . $row->{'title'} . "\n";
245         $current .= "X-SC-Location: " . $row->{'location'} . "\n";
246         $current .= "X-SC-Category: School\n";
247         $current .= "X-SC-Cond: " . $row->{'days'} . "\n";
248         $current .= "X-SC-Time: ".$row->{'begin'}."-".$row->{'end'}."\n";
249         $current .= "X-SC-Duration: " . $row->{'duration'} . "\n";
250         $current .= "X-SC-Day: @day\n" if(exists $day[0]);
251         $current .= "X-SC-Alarm: 15 minutes\n";
252         $current .= "X-SC-Record-Id: <".$row->{'id'}."\@from.sctweb>\n";
253         if(defined($file) && (-d $file)) {
254             my $email = get_faculty_email $row->{'instructor'};
255             $row->{'instructor'} = '"' . $row->{'instructor'} . '" <'. ($email || ($1 || "unknown") . "\@from.sctweb") . ">";
256             $row->{'duration'} =~ /^(\d\d\d\d)(\d\d)(\d\d)-\d{8}$/;
257             $row->{'begin'} =~ /^(\d\d):(\d\d)$/;
258             my $next = next_class(%$row);
259             my @date = Gmtime(Mktime($next->date,$1,$2,0));
260             $current .= sprintf "Date: %s, %2d %s %4d %02d:%02d:00 +0000\n", Day_of_Week_Abbreviation($date[7]), $date[2], $mon[$date[1]-1], $date[0], $date[3], $date[4], $date[5];
261             $current .= "Subject: " . $row->{'title'} . "\n";
262             $current .= "From: " . $row->{'instructor'} . "\n";
263         }
264         #print "\n$current";
265         push @mhc, $current;
266     }
267     if(defined($file) && (-d $file)) {
268         my @lines;
269         foreach my $name (<$file/[1-9]*>) {
270             next unless $name =~ /^$file\/[1-9][0-9]*$/;
271             open FH, $name;
272             @lines = <FH>;
273             close FH;
274             foreach (@lines) {
275                 unlink $name if /^X-SC-Record-Id: <.*\@from.sctweb>/;
276             }
277         }
278         my $i=0;
279         foreach (@mhc) {
280             while(-f ++$i) {}
281             open FH, ">$file/$i" or die $!;
282             print FH $_;
283             close FH;
284         }
285     } else {
286         open(STDOUT, ">" . $file) if(defined($file));
287         print "# MHC school schedule\n# Autogenerated by sctweb ".localtime()."\n\n";
288         print join("\n", @mhc);
289     }
290 }
291
292 sub do_csv_schedule {
293     $| = 1;
294     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
295     my @mon = qw(Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.);
296     my ($current, @mhc, @schedule);
297     @schedule = get_schedule(@_);
298     open(STDOUT, ">" . $opts{'out'}) if(defined($opts{'out'}));
299     foreach my $row (@schedule) {
300         map {s/\n/-/g if defined; $_} %$row;
301         my $id=generate_id($row->{'id'});
302         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
303         $row->{'days'} =~ s/^ //;
304         my $next = next_class(%$row);
305         $current = "";
306         #print "# $id\n";
307         $current .= $row->{'id'} . ",";
308         $current .= $row->{'title'} . ",";
309         my $instructor = $row->{'instructor'};
310         $instructor =~ s/ [A-Z. ]* / /;
311         $current .= '"' . $instructor . '",';
312         $next =~ /^(\d\d\d\d)(\d\d)(\d\d)$/;
313         $current .= $1 . "-". $2 ."-" . $3 . "\n";
314         print $current;
315     }
316 }
317
318 sub do_vcalendar_schedule {
319     $| = 1;
320     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
321     my $file = $opts{'out'};
322     my @schedule = get_schedule(@_);
323     open(STDOUT, ">>" . $file) if(defined($file) && (! -d $file));
324     open(STDOUT, ">/dev/null") if(defined($file) && (-d $file));
325     print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
326     foreach my $row (@schedule) {
327         map { s/\n/-/g; $_} %$row;
328         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
329         $row->{'days'} =~ s/^ //;
330         my @day = ();
331         @day = @{$row->{'off'}} if ($row->{'off'});
332         my $day = "";
333         if(exists($day[0])) {
334             $day = join(";", @day);
335             $day =~ s/\b(\d{8})\b/$1T000000/g;
336         }
337         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
338         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
339         $starttime =~ s/://;
340         $stoptime =~ s/://;
341         if(defined($file) && (-d $file)) {
342             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
343             select FH;
344             print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
345         }
346         print "BEGIN:VEVENT\r\n";
347         print "SUMMARY:", $row->{'title'}, "\r\n";
348         print "DESCRIPTION:", $row->{'id'}, "\r\n";
349         print "LOCATION:", $row->{'location'}, "\r\n";
350         print "CATEGORIES:Education\r\n";
351         print "DTSTART:", $startdate."T".$starttime, "00\r\n";
352         print "DTEND:", $startdate."T".$stoptime, "00\r\n";
353         print "RRULE:W1 ", $row->{'days'} . " $stopdate", "T000000\r\n";
354         print("EXDATE:$day\r\n") if($day);
355         print "ATTENDEE;ROLE=OWNER;STATUS=CONFIRMED:", $opts{'name'}, "\r\n" if(defined($opts{'name'}));
356         print "ATTENDEE;ROLE=ORGANIZER;STATUS=CONFIRMED:", $row->{'instructor'}, " <" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), ">\r\n";
357         print "END:VEVENT\r\n";
358         if(defined($file) && (-d $file)) {
359             print "END:VCALENDAR\r\n";
360             close FH;
361             select STDOUT;
362         }
363     }
364     print "END:VCALENDAR\r\n";
365 }
366
367 sub do_xml_schedule {
368     my $file = $opts{'out'};
369     my $schedule = { class => [ get_schedule(@_) ] };
370     my $xml = XMLout($schedule, NoAttr => 1, RootName => 'schedule');
371     if($file) {
372         open FH, ">$file";
373         print FH $xml;
374         close FH;
375     } else {
376         print $xml;
377     }
378 }
379
380 sub do_html_schedule {
381     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
382     my $shade = "dark";
383     my @schedule = get_schedule(@_);
384     if($opts{'out'}) {
385         open FH, ">" . $opts{'out'};
386         select FH;
387     }
388     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
389     print join("</th><th>",@showheaders);
390     print "</th></tr>\n";
391         foreach my $row (@schedule) {
392             map { s/\n/<br \/>/g; $_} %$row;
393             $row->{'duration'} =~ s/-/<br \/>/g;
394             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
395             print '<tr class="'.$shade.'">';
396             $shade = ($shade eq "dark"?"light":"dark");
397             print '<td class="idtitle">';
398             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
399             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
400             my $instructor = $row->{'instructor'};
401             #$instructor =~ s/ [A-Z. ]* / /;
402             my $email = get_faculty_email($row->{'instructor'});
403             #if($email) {
404                 #print '<td><a href="mailto:' . $email . '">'
405                 #. $row->{'instructor'} . "</a></td>";
406             # } else {
407             print "<td>" . $instructor . "</td>";
408             #}
409             print "<td>" . $row->{'days'} . "</td>";
410             my ($a,$b) = ($row->{'begin'}, $row->{'end'});
411             $b .= "AM";
412             $a=~s/(1[3-9]|2\d|00):(\d\d)/sprintf "%d:%02d",abs $1-12,$2/e;
413             $b=~s/(1[3-9]|2\d|00):(\d\d)AM/sprintf "%d:%02dPM",abs $1-12,$2/e;
414             print "<td>$a-<wbr />$b</td>";
415             print "<td>" . $row->{'duration'} . "</td>";
416             print "<td>" . $row->{'location'} . "</td>";
417             print "</tr>\n";
418         }
419     print "</table>\n";
420     select STDOUT;
421 }
422
423 sub do_html_grades {
424     my $grades;
425     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
426     $grades = get_grades(@_);
427     my ($row);
428     my $shade = "dark";
429     if($opts{'out'}) {
430         open FH, ">" . $opts{'out'};
431         select FH;
432     }
433     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
434     print '<th align="left" class="sectionid">', $showheaders[0];
435     print '</th><th align="left" class="coursetitle">', $showheaders[1];
436     print '</th><th align="center" class="grade">';
437     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
438     print "</th></tr>\n";
439     foreach my $ts ($grades->{'class'}) {
440         foreach my $row (@$ts) {
441             print '<tr class="'.$shade.'">';
442             $shade = ($shade eq "dark"?"light":"dark");
443             print '<td align="left" class="sectionid">', $row->{'id'}, '</td>';
444             print '<td align="left" class="coursetitle">', $row->{'title'}, '</td>';
445             print '<td align="center" class="grade">';
446             #print join('</td><td>', @$row[0 .. 1]);
447             print join('</td><td align="right" class="right-number">', ($row->{'grade'},$row->{'earned'},$row->{'hours'},$row->{'points'}));
448             print "</td></tr>\n";
449         }
450     }
451     my $lastrow = $grades->{'cumulative'}->[scalar @{$grades->{'cumulative'}}-1];
452     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">Cumulative: through ', capitalize($lastrow->{'term'});
453     print '</td><td align="center" id="gpa" class="grade">';
454     print $lastrow->{'gpa'};
455     print '</td><td align="right" class="right-number">';
456     print join('</td><td align="right" class="right-number">', ($lastrow->{'earned'}, $lastrow->{'hours'}, $lastrow->{'points'}));
457     print "</td></tr>\n";
458     print "</table>\n";
459     select STDOUT;
460 }
461
462
463 if ($opts{'format'} eq "xml") {
464     do_xml_schedule(@ARGV);
465 } elsif ($opts{'format'} eq "html") {
466     do_html_schedule(@ARGV);
467 } elsif ($opts{'format'} eq "mhc") {
468     do_mhc_schedule(@ARGV);
469 } elsif ($opts{'format'} eq "csv") {
470     do_csv_schedule(@ARGV);
471 } elsif ($opts{'format'} eq "vcs") {
472     do_vcalendar_schedule(@ARGV);
473 } elsif ($opts{'format'} eq "grades") {
474     do_html_grades(@ARGV);
475 } else {
476     die "Unknown format.  Try specifying --format.\n"
477 }
478