#!perl
use XML::Simple;
use Data::Dumper;
$xml = new XML::Simple;
$data = $xml->XMLin("mailFilters.xml");
# Build hashes of arrays one for each type (to, from, subject) with the destination as key, and search values as array values
%from = ();
foreach $filter (keys %{$data->{entry}}){
	push @{$from{$data->{entry}->{$filter}->{"apps:property"}->{"label"}->{"value"}}}, $data->{entry}->{$filter}->{"apps:property"}->{"from"}->{"value"}
	if ( length($data->{entry}->{$filter}->{"apps:property"}->{"from"}->{"value"}) > 0 && length($data->{entry}->{$filter}->{"apps:property"}->{"label"}->{"value"}) > 0);
}
%to = ();
foreach $filter (keys %{$data->{entry}}){
        push @{$to{$data->{entry}->{$filter}->{"apps:property"}->{"label"}->{"value"}}}, $data->{entry}->{$filter}->{"apps:property"}->{"to"}->{"value"}
           if ( length($data->{entry}->{$filter}->{"apps:property"}->{"to"}->{"value"}) > 0 && length($data->{entry}->{$filter}->{"apps:property"}->{"label"}->{"value"}) > 0);
}
%subject = ();
foreach $filter (keys %{$data->{entry}}){
        push @{$subject{$data->{entry}->{$filter}->{"apps:property"}->{"label"}->{"value"}}}, $data->{entry}->{$filter}->{"apps:property"}->{"subject"}->{"value"}
           if ( length($data->{entry}->{$filter}->{"apps:property"}->{"subject"}->{"value"}) > 0 && length($data->{entry}->{$filter}->{"apps:property"}->{"label"}->{"value"}) > 0);
}
# Print out sieve rules from our hashes:
print "require [\"fileinto\"];\n";
foreach $rule (keys %from){
	print "\n# rule:[from-$rule]\n";
	print "if any of (";
	$i=0;
	foreach $value (@{$from{$rule}}){
		print ",\n\t" if $i>0;
		print "header :contains \"From\" \"$value\"";
		$i++;
	}
	print " )\n\t{\n\t\tfileinto \"$rule\";\n\t}\n"
}
foreach $rule (keys %to){
        print "\n# rule:[to-$rule]\n";
        print "if any of (";
        $i=0;
        foreach $value (@{$to{$rule}}){
                print ",\n\t" if $i>0;
                print "header :contains \"To\" \"$value\"";
                $i++;
        }
        print " )\n\t{\n\t\tfileinto \"$rule\";\n\t}\n"
}
foreach $rule (keys %subject){
        print "\n# rule:[subject-$rule]\n";
        print "if any of (";
        $i=0;
        foreach $value (@{$subject{$rule}}){
                print ",\n\t" if $i>0;
                print "header :contains \"Subject\" \"$value\"";
                $i++;
        }
        print " )\n\t{\n\t\tfileinto \"$rule\";\n\t}\n"
}
