#!/usr/bin/perl -w
#
#  Copyright owner:  Paul Millar <paul@astro.gla.ac.uk>
#  Copyright BSD-like license:  do what you want, but don't remove this
#                               license
#
#  CVS id $Id: bulkNoCheckMail.pl,v 1.11 2007-03-19 15:43:29 paul Exp $
#  Version 0.2
#
#  Simple script for uncheckbox-ing the check-mail in kmail.  Please email
#  me diffs of changes.


#  The IMAP server
my $IMAP="Physics and Astronomy";
#my $IMAP="othello";
my $test_id;

$ARGV[0] || die "No path given.  I need to know under which directories new mail should\nbe ignored\n";

# First, find the ID number for the server.  This is problematic as
# the ID might come before the Name.
#
open KDERC,$ENV{HOME}."/.kde/share/config/kmailrc" || die "Cannot open kmailrc file";
$state=0;
while( <KDERC>) {

    chomp;

    if ( $state == 0) {
	$state=1 if /\[Account [0-9]*\]/;
    } elsif ( $state == 1) {
	if ( /[Ii][Dd] *= *([^ ]*)/) {
	    $test_id=$1;
	    $state=2;
	}

	$state=3  if( /[nN]ame *= *$IMAP/);

    } elsif ( ($state == 2) && (/[nN]ame *= *$IMAP/)) {
	$id = $test_id;
	last;
    } elsif ( ($state == 3) && ( /[Ii][Dd] *= *([^ ]*)/)) {
	$id = $1;
	last;
    }

    $state=0 if( /^ *$/)  
}
close KDERC;

# $ARGV[0] is exploded around naked "/"s to \\.$dir\\.directory
@dirs = split( /\//, $ARGV[0]);
foreach (@dirs)
{
  $_ = "\\." . $_ . "\\.directory" ;
}

# This should remap " "s to "%20"s in $IMAP
my $searchIMAP = $IMAP;
$searchIMAP =~ s/ /%20/g;

my $re1= "^\\[Folder-\\.$searchIMAP\\.directory/".join ("/", @dirs);
my $re2= "^\\[Folder-\\.$id\\.directory/".join ("/", @dirs) if $id;

open KDERC,$ENV{HOME}."/.kde/share/config/kmailrc" || die "Cannot open kmailrc file";
open NEW,">/tmp/new-kmailrc" || die "Cannot create new file";

my $changed=0;
my $count=0;
my $inside=0;

while( <KDERC>) {
#    Folders look like:
#  [Folder-.<IMAP name>.directory/.<dir1>.directory/.<dir2>.directory/...]
#    or
#  [Folder-.<IMAP id>.directory/.<dir1>.directory/.<dir2>.directory/...]
#  
    $inside=1 if( (/$re1/) || ($id && /$re2/));

    $inside=0 if( /^$/);
    
    /^checkmail=/ && $count++; 

    if( $inside) {
	if( /^checkmail=true/ ) {
	    s/^checkmail=true/checkmail=false/;
	    $changed++;
	}
    }

    print NEW;
}

close NEW;
close KDERC;

print "New config is /tmp/new-kmailrc, which changed $changed (of $count) entries.\n";

