#!/usr/bin/perl 

# Converts procmail filter rules to kmail filter rules

# Copyright (c) 2002-2004 Steffen Pingel
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
#  o Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 
#  o Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
# 
#  o Neither the name of JGoodies Karsten Lentzsch nor the names of
#    its contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#
# Each rule in ~/.procmailrc is expected to have the following format:
#  
#  :0:
#  * ^(CC|To):.*@lists.debian.org\
#  |^(CC|To):.*@bugs.debian.org
#  Debian
#

print "This script will kill all your existing kmail filters.\n";
print "It will only run if the exit statement is removed.\n";
exit 1;

$state = 0;
my @content;
open(IN, "<$ENV{'HOME'}/.kde/share/config/kmailrc") or die("could not open ~/.kde/share/config/kmailrc");
while (my $line = <IN>) {
	if ($line =~ /^\[Filter \#/) {
		$state = 1;
	}
	elsif ($line =~ /^\[/) {
		$state = 0;
	}
	
	if ($state == 0) {
		push @content, $line;
	}
}
close(IN);

open(IN, "<$ENV{'HOME'}/.procmailrc") or die("could not open ~/.procmailrc");

my @rules;
my $filterCount = 0;

$state = 0; # waiting for rule
while (my $line = <IN>) {
	chomp $line;
	if ($state == 0 
		&& ($line =~ "^\:0\:")) {

		$state = 1;
		$#rules = 0;
		#print "New rule\n";
	} 
	elsif ($state == 1 
		   && ($line =~ "^\\*" || $line =~ "^|")) {

		if ($line !~ "\\\\\$") {
			# no backslash at line end, last line for this rule
			$state = 2;
		} 
		else {
			# remove trailing backslash
			$line =~ s/\\$//;
		}

		# remove | and ^ character
		$line =~ s/^\* \^//;
		$line =~ s/^\|\^//;
		
		my $rule;
		($fields, $match) = split(/:/, $line, 2);

		# remove parenthesis
		$fields =~ s/^\(//;
		$fields =~ s/\)$//;
		$match =~ s/^(\.\*| )//;
		
		my @tokens = split('\|', $fields);
		foreach $field (@tokens) {
			#print "$field: $match\n";
			push @rules, $field, $match;
		}
	} 
	elsif ($state == 2
		   && $line ne "") {
		# remove backslashes
		$line =~ s/\\//;

		# inbox is default folder
		$line =~ s/\$DEFAULT/inbox/;

		# convert to kmail directory names
		my $directory;
		my @tokens = split('/', $line);
		my $lasttoken = pop @tokens;
		foreach $token (@tokens) {
			# make sure all parent directories exist
			create_maildir("$directory/$token", true);

			$directory .= ".$token.directory/";
			create_maildir("$directory", false);
		}
		$directory .= $lasttoken;
		#print "Folder: $directory\n\n";
		$state = 0;

		# create directory on disk
		create_maildir($directory, true);

		# add section to kmailrc
		push @content, "[Filter #$filterCount]\n";
		push @content, "ConfigureShortcut=false\n";
		push @content, "ConfigureToolbar=false\n";
		push @content, "Icon=\n";
		push @content, "StopProcessingHere=true\n";
		push @content, "action-args-0=$directory\n";
		push @content, "action-name-0=transfer\n";
		push @content, "actions=1\n";
		push @content, "apply-on=check-mail,manual-filtering\n";
		push @content, "name=$lasttoken\n";
		push @content, "operator=or\n";
		my $ruleCount = $#rules / 2;
		push @content, "rules=$ruleCount\n";
		$ruleCount = 'A';
		while(my $match = pop @rules) {
			my $field = pop @rules;
			push @content, "contents$ruleCount=$match\n";
			push @content, "field$ruleCount=$field\n";
			push @content, "func$ruleCount=regexp\n";
			$ruleCount++;
		}
		push @content, "\n";
		$filterCount++;
	}
}

close IN;

$state = 0;
$i = 0;
for (@content) {
	if (/\[General\]/) {
		$state = 1;
	}
	elsif ($state == 1
		   && /^filters=/) {
		$_ = "filters=$filterCount\n";
	}
	elsif (/^\[/) {
		$state = 0;
	}
	$i++;
}

open(OUT, ">$ENV{'HOME'}/.kde/share/config/kmailrc") or die("could not open ~/.kde/share/config/kmailrc");
print OUT @content;
close(OUT);

exit 0;



sub create_maildir {
	my $directory = shift;
	my $storesMail = shift;
	my $path = "$ENV{'HOME'}/Mail/$directory";
	mkdir "$path", 0700;
	if ($storesMail) {
		mkdir "$path/cur", 0700;
		mkdir "$path/new", 0700;
		mkdir "$path/tmp", 0700;
	}
}

