#!/usr/bin/env perl

# author: ryan king <ryan@theryanking.com>

#usage:
# cat some_file.ics | ./normalize.pl FOO:bar
#
#  this will normalize (ie, sort lexically, the properties in the objects) and replace
#   all instances of '$FOO$' with 'bar' and print the results to STDOUT.

use strict;
use URI;
my %regexes;
my %url_regexes;

foreach my $arg (@ARGV){
    if ($arg =~ /\$([A-Z\-]+)\:(.*)/) {
        $url_regexes {'$' . $1 . '$(.*)$'} = $2;
        $regexes{"\$" . $1 . "\$"} = $2;
    } elsif ($arg =~ /([A-Z\-]+)\:(.*)/){
        $regexes{"\$" . $1 . "\$"} = $2;
    } else {
        die "I dunno what to do with $arg";
    }
}

normalize_object();

sub normalize_object {
    my @buffer;
    while(<STDIN>){
        #if blank
        if($_ =~ /^\s+$/){
            #pass
        } elsif ($_ =~ /^BEGIN\:[A-Z]+/) {
            #sort collection, output
            foreach (sort @buffer) {
                print_filtered($_);
            }
            @buffer = ();
            print;
            #recurse to do nested objects
            normalize_object()
        } elsif ($_ =~ /^END\:[A-Z]+/){
            foreach( sort @buffer){
                print_filtered($_);
            }
            @buffer = ();
            print;
            return;
        } elsif($_ =~ /^[A-Z]*/) {
            #collect lines in the object
            push(@buffer,$_);
        }
    }
}

sub print_filtered {
    my $line  = shift;

    while( my($k, $v) = each %url_regexes){
        my $r = $k;
        $r =~ s/([\$\-])/\\$1/g;
        while($line =~ /^(.*)($r)(.*)$/g){
            print $1 . URI->new_abs($3, $v)->canonical. "\n";
            return;
        }
    }
    my $search = join('|', keys %regexes);
    $search =~ s/([\$\-])/\\$1/g;
    $line =~ s/($search)/$regexes{$1}/;
    print $line;
}
