#!/usr/bin/env python

""" import and export kmail filters """

import sys
import os
import re
from optparse import OptionParser
from ConfigParser import RawConfigParser
from tempfile import NamedTemporaryFile
from subprocess import call


KMAILRC_PATH = "~/.kde/share/config/kmailrc"
KMAILRC = os.path.expanduser(KMAILRC_PATH)
SNAME_PAT = re.compile(r"^\[(.*)\]")

def sections(path):
    data = open(path).read()
    return [(s.startswith("[") and s or "[" + s).strip()
            for s in data.split("\n[")]


def sect_name(sect):
    return SNAME_PAT.match(sect).group(1)


def conf_filters(conf):
    return [s for s in conf.sections() if s.startswith("Filter ")]


def filters(path):
    return [s for s in sections(path)
            if sect_name(s).startswith("Filter ")]


def export_filters(opts):
    if opts.outfile:
        out = open(opts.outfile, "w")
    else:
        out = sys.stdout
    out.write("\n\n".join(filters(KMAILRC)))
    out.write("\n")


def import_filters(opts):
    sects = [s for s in sections(KMAILRC)
             if not sect_name(s).startswith("Filter ")]

    new_filters = filters(opts.infile)

    def set_nb(sect):
        if sect_name(sect) == "General":
            return re.sub("(filters=\d+)",
                          "filters=%s" % len(new_filters),
                          sect)
        else:
            return sect
    
    data = "\n\n".join(map(set_nb, sects)+new_filters)
    open(KMAILRC, "w").write(data+"\n")
    

def scp_filters(opts):
    tmp = NamedTemporaryFile("r")
    if call(["scp", "%s:%s" % (opts.host, KMAILRC_PATH), tmp.name]):
        print "can't scp"
        sys.exit(1)
    opts.infile = tmp.name
    import_filters(opts)


def main():
    parser = OptionParser(usage="%prog: [OPTIONS]")

    parser.add_option("-o", "--output", dest="outfile", default=None,
                      help="output to FILE")
    
    parser.add_option("-i", "--import", dest="infile",
                      help="import filters from INFILE")

    parser.add_option("-H", "--host", dest="host",
                      help="use the filters on HOST")

    (opts, args) = parser.parse_args()

    if args:
        parser.print_help()
        sys.exit(1)

    if opts.infile:
        import_filters(opts)
    elif opts.host:
        scp_filters(opts)
    else:
        export_filters(opts)


if __name__ == "__main__":
    main()
    

