#!/usr/bin/perl
# pal2ics - pal to korganizer converter
# Done 2006 by Jonas Mitschang, jonen@mitschang.net
#
# This script converts PAL calendar files to the vCalendar format
# The vCalendar format can be imported by korganizer
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# If you improve this script, please send me a copy.
#
# Usage:
#   cat foo.pal | pal2ics > foo.ics
#
use strict;

# create alarm entries for the birthdays?
my $alarm = 0;

##############################################################################

# program usage
sub usage {
    printf "Usage: cat foo.pal | pal2ics > foo.ics\n";
    exit 0;
}

# parameter supplied? show usage
&usage if $ARGV[0];

# 20061109T231130Z
chomp(my $dtstamp = `date +%Y%m%dT%H%M%SZ`);

# header
printf <<EOF;
BEGIN:VCALENDAR
PRODID:-//K Desktop Environment//NONSGML KOrganizer 3.5.5//EN
VERSION:2.0
EOF

# example todo entry:
#BEGIN:VTODO
#DTSTAMP:20061109T231130Z
#ORGANIZER;CN=Jonas Mitschang:MAILTO:jonen@mitschang.net
#CREATED:20061108T195856Z
#UID:KOrganizer-1196745506.1129
#SEQUENCE:2
#LAST-MODIFIED:20061108T195901Z
#SUMMARY:test
#CLASS:PUBLIC
#PRIORITY:5
#PERCENT-COMPLETE:0
#END:VTODO

# process all lines from standard input
my $count = 0;
while (<>) {
    # remove \n and skip empty lines
    chomp;
    next unless $_;

    # pal entry syntax: yyyymmdd text
    # where text may be several comma separated names
    if (my ($year, $month, $day, $names) = /(\d\d\d\d)(\d\d)(\d\d)\s(.*)/) {
        # birthday entries should appear every year
        if ($year eq "0000") {
            foreach my $name (split /\s*,\s*/, $names) {
                $count++;

                # convert lowercase names to uppercase
                $name =~ s/(\W+)(\w)/"$1".uc $2/ge;
                $name =~ s/^(\w)/uc $1/ge;

                # create entry
                printf <<EOF;

BEGIN:VEVENT
DTSTAMP:$dtstamp
ORGANIZER:MAILTO:
X-KDE-KABC-BIRTHDAY:YES
X-KDE-KABC-NAME-1:$name
CREATED:$dtstamp
LAST-MODIFIED:$dtstamp
SUMMARY:$name - Geburtstag
CLASS:PUBLIC
PRIORITY:5
CATEGORIES:Geburtstag
RRULE:FREQ=YEARLY
DTSTART;VALUE=DATE:$year$month$day
DTEND;VALUE=DATE:$year$month$day
TRANSP:TRANSPARENT
EOF
                # add alarm entry if desired
                if ($alarm) {
                    printf <<EOF;
BEGIN:VALARM
ACTION:
TRIGGER;VALUE=DURATION:PT0S
END:VALARM
EOF
                }
                printf "END:VEVENT\n";
            }
        } else {
            printf STDERR "No birthday: $_\n";
        }
    } else {
        printf STDERR "No pal event: $_\n";
    }
}

# footer
printf <<EOF;
END:VCALENDAR
EOF

# status message to stderr
printf STDERR "Processed $count birthdays\n";

