#!/usr/bin/perl
#
# $Id: ipod-cal.pl,v 1.2 2006/09/19 22:08:18 cvsremote Exp $
#
# Usage: ipod-cal [-help | -new | ical-url]
#

$CalUrlFile = "$ENV{HOME}/.ipod-cal";
$CalFile = "basic.ics";


# Check if $CalUrlFile exists. Create one if not.
#
createCalUrlFile("$CalUrlFile") unless (-f "$CalUrlFile");
if ($#ARGV >= 0) {
    usage() if ($ARGV[0] =~ /\-h/);
    if ($ARGV[0] =~ /\-new/) {
        shift;
        createCalUrlFile("$CalUrlFile");
        require "$CalUrlFile";
    } else {
        $URL = "$ARGV[0]";
    }
} else {
    require "$CalUrlFile";
    if (!defined($URL) || $URL eq '') {
        die "No Calender URL in $CalUrlFile.\n";
    }
}

$drives = `ls /cygdrive`;
chop($drives);
@drives = split(/[ \t\n]+/, $drives);
@drives = sort {$b cmp $a;} @drives;
chop($cwd = `pwd`);
foreach $drive (@drives) {
    $dir = "/cygdrive/$drive/Calendars";
    next unless (-d "$dir");

    chdir("$dir") || die "Error: chdir($dir)\n";
    if (-f "$CalFile") {
        unless (rename("$CalFile", "$CalFile.BAK")) {
            if (unlink("$CalFile") < 1) {
                printf(STDERR "Can't remove $CalFile.\n");
            }
        }
    }
    $rv = system("wget $URL");
    if ($rv) {
        printf(STDERR "Error: wget(%d)\n", $rv >> 8);
        if (-f "$CalFile.BAK") {
            unless (rename("$CalFile.BAK", "$CalFile")) {
                if (unlink("$CalFile.BAK") < 1) {
                    printf(STDERR "Can't remove $CalFile.BAK.\n");
                }
            }
        }
    } else {
        unlink("$CalFile.BAK");
    }
    $rv = 1 unless (chdir("$cwd"));
    exit($rv);
}

printf(STDERR "No iPod found.\n");
exit(1);


sub createCalUrlFile {
    my($file) = @_;
    my($fd, $url);

    unless(open($fd, ">$file")) {
        print(STDERR "Error: Can't write open $file\n");
        return;
    }
    $url = '';
    while($url eq '') {
        printf(STDERR "Calendar URL: ");
        $url = <>;
        chop($url);
    }
    print $fd '$URL = ' . "'" . "$url" . "';\n";
    close($fd);
}


sub usage {
    print STDERR "Usage: ipod-cal [-help | -new | ical-url]\n";
    exit(1);
}
