#!/usr/bin/perl

use Tie::iCal;
use Date::ICal;

$ofs = 'PT9H';
$basedir = "/home/nakano/text/diary";

$gcalics_n = 'http://www.google.com/calendar/ical/nakanot@gmail.com/public/basic.ics';
$gcalics_l = '¤Ê¤¤¤·¤ç';

$icsfile_n = 'nakano.ics';
$icsfile_l = 'labo.ics';

system ("wget $gcalics_n; mv basic.ics $icsfile_n");
system ("wget $gcalics_l; mv basic.ics $icsfile_l");

foreach $icsfile ($icsfile_n, $icsfile_l){
tie %my_events, 'Tie::iCal', $icsfile;
while (my($uid, $event) = each(%my_events)){
        if (${$event}[0] ne 'VEVENT'){next;};
        %ent = %{${$event}[1]};

        $summary = $ent{'SUMMARY'};
	if ($summary eq 'Busy'){next;}

	$location = $ent{'LOCATION'};
	if (ref($location) ne 'ARRAY' && $location =~ /\S/) {
		 $summary .= '@' . $location;
	}

	if ($ent{'DTSTART'}[0]{'VALUE'} eq "DATE"){ $date = 1; }
	else { $date = 0; }
	$time = Date::ICal->new (ical => $ent{'DTSTART'}[1]) +$ofs;

	if ($ent{'RRULE'} ne "") {

		$end = Date::ICal->new (ical => $ent{'RRULE'}{'UNTIL'}) +$ofs;

		$interval = $ent{'RRULE'}{'INTERVAL'};
		if ($interval eq ""){ $interval = 1 }
		$freq = $ent{'RRULE'}{'FREQ'};
		if ($freq eq 'WEEKLY') { $duration = sprintf "P%1dW", $interval;}
		elsif ($freq eq 'DAILY') { $duration = sprintf "P%1dD", $interval;}
		else {die 'RRULE_FREQ is not WEEKLY nor DAILY';}

		if ( ref($ent{'EXDATE'}[0]) eq 'HASH'){
			@exdate = ( Date::ICal->new (ical=>$ent{'EXDATE'}[1]) + $ofs );
		} else {
			@exdate = ();
			for ($i=0; $i<$#{$ent{'EXDATE'}}; $i++){
				push @exdate, Date::ICal->new (ical=>$ent{'EXDATE'}[$i][1]) + $ofs;
			}
		}
	} else {
		$end = Date::ICal->new (ical => $ent{'DTEND'}[1])+$ofs;
		$freq = "NONE";
		$duration = 'P1D';
	}

	if ($freq eq 'DAILY'){
		$summary .= sprintf " [%02d/%02d-]", $time->month, $time->day;
		$time = $end->clone;
	}

	if ($date == 1 && $end > $time + 'P1D'){
		$summary .= sprintf " [%02d/%02d-]", $time->month, $time->day;
		$time = $end - 'PT9H1M';
	}

	do {
		$ex = 0;
		for($i=0;$i<=$#exdate;$i++){
			if ($exdate[$i] == $time) {$ex = 1;}
		}

		$calendar = sprintf "%02d/%02d", $time->month, $time->day;

		if ($date){$clock = "";}
		else {
			$clock = sprintf " [%02d:%02d]",
				$time->hour, $time->min;
		}

		unless ($ex){
			$ym = sprintf "%04d%02d", $time->year, $time->month;
			$content{$ym} .= "$calendar $summary$clock\n";
		}
		$time += $duration;
	} while ($freq eq 'WEEKLY' && $time <= $end);
}
untie %my_events;
}

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
$curyear = sprintf "%04d", $year + 1900;

while (($key, $value) = each (%content)) {
	$key =~ /^([12][0-9]{3})/;
	$year = $1;
	if ($year < $curyear){next;}
	$dir = "$basedir/$year";
	$path = "$dir/y$key";

#	print "$key\n$value";
	
	system "mkdir -p $basedir/$year/";
	if ( -f $path ) { system "mv -f $path $path.orig"; }
	open OUT, "| nkf -e >> $path" or die "cannot open $path for writing";
	print OUT $value;
	close OUT;
}
#unlink $icsfile;

