#!/usr/bin/env perl

use strict;
use CGI qw(standard);
use File::Basename;
use Cwd qw(realpath);

BEGIN {
    unshift(@INC, realpath(dirname($0)));
}
use PurePerl qw(sha256_hex);

my $q = new CGI;

my @optionals = (
    [ 'summary', 'summary' ],
    [ 'description', 'desc' ],
    [ 'location', 'loc' ],
    [ 'url', 'url' ],
    [ 'status', 'stat' ],
);

my $uid = sha256_hex($q->param('styear').$q->param('summary').$q->param('stmon').$q->param('stday'));

print <<EOF;
Content-type: application/rdf+xml
Content-Disposition: attachment; filename=cal.rdf

<?xml version="1.0"?>
<rdf:RDF xml:lang="en"
         xmlns="http://www.w3.org/2002/12/cal/ical#"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<!--
  =======================================================================

   Copyright (c) 2006 The Apache Software Foundation.
   All rights reserved.

  =======================================================================
-->
  <version>2.0</version>
  <Vevent>
EOF
my $startdt;
if ($q->param('styear')) {
    $startdt = sprintf("%04d-%02d-%02d", $q->param('styear'),
                       $q->param('stmon'), $q->param('stday'));
    print "    <dtstart>$startdt";
    if ($q->param('sthr') != -1 ) {
        printf("T%02d:%02d:00Z", $q->param('sthr'), $q->param('stmin'));
    }
    print "</dtstart>\n";
}
if ($q->param('fyear') != -1 || $q->param('fhr') != -1) {
    print "    <dtend>";
    
    printf("%04d-%02d-%02d", $q->param('fyear'),
           $q->param('fmon'), $q->param('fday')) if $q->param('fyear') != -1 ;
    print $startdt if $q->param('fyear') == -1;

    if ($q->param('fhr') != -1) {
        printf("T%02d:%02d:00Z", $q->param('fhr'), $q->param('fmin'));
    }
    print "</dtend>\n";
}

foreach my $arr (@optionals) {
    my $v = $q->param($arr->[1]);
    print "    <$arr->[0]>$v</$arr->[0]>\n" if $v;
}
if (($q->param('durh') + $q->param('durm')) > 0) {
    print "    <duration>PT";
    print $q->param('durh')."H" if $q->param('durh') > 0;
    print $q->param('durm')."M" if $q->param('durm') > 0;
    print "</duration>\n";
}
if ($q->param('orgnm')) {
    print "    <organizer><cn>".$q->param('orgnm')."</cn></organizer>\n";
}
print <<EOF;
    <uid>$uid</uid>
    <class>PUBLIC</class>
  </Vevent>
</rdf:RDF>
EOF

