#!/usr/bin/python
# Filename:      hgrc
# Purpose:       edit multiple repository configs
# Authors:       grml-team (grml.org), (c) Michael Gebetsroither <gebi@grml.org>
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2.
################################################################################

import os
import sys
import optparse
import re
from ConfigParser import SafeConfigParser as ConfigParser

from hgutil.hg.util import *
from hgutil.hg.simple import syncRepos
from hgutil.exception import CmdException
from hgutil.util import DirChanger 

sep ="----------------------------------------------------------------------"  

def create_uri(string):
    target = string.split(':', 1)
    if len(target) == 1:
        target.insert(0, "")
    return target[0], target[1]


def action_dump(path, args, opts):
    cfg = ConfigParser()
    cfg.read(path + "/.hg/hgrc")
    print sep
    print path
    cfg.write(sys.stdout)

def action_get(path, args, opts):
    cfg = ConfigParser()
    cfg.read(path + "/.hg/hgrc")
    section, key = create_uri(args[0])
    value = None
    try:
        value = cfg.get(section, key)
    except:
        pass
    print "%s: %s" % (path, value)

def action_set(path, args, opts):
    fd = open(path + "/.hg/hgrc")
    cfg = ConfigParser()
    cfg.readfp(fd)
    cfg.set("", "autohgrc", "True")
    section, key = create_uri(args[0])
    if not cfg.has_section(section):
        cfg.add_section(section)
    cfg.set(section, key, args[1])
    print sep
    print path
    cfg.write(sys.stdout)
    fd.close()

def run(src, cmd, args, opts):
    imatch = re.compile(opts.ignore)
    srcfunc = walkrepos_flat
    if opts.recursive:
        srcfunc = walkrepos
    error = True
    for path in srcfunc(src):
        path = path.rstrip(os.path.sep)
        if imatch.search(path) != None:
            continue
        dir = DirChanger(path)
        try:
            cmd(path, args, opts)
        finally:
            dir.down()
    return error

if __name__ == '__main__':
    cmdlist = {
            "dump": (action_dump, "Dump config"),
            "get": (action_get, "Get config value"),
            "set": (action_set, "Set config value")
            }
    parser = optparse.OptionParser(usage="usage: %prog [options] <src> <command> [ <args> ]")
    parser.add_option("-i", "--ignore", dest="ignore", default="""(?!)""", metavar="regexp",
            help="Filter list of repository names")
    parser.add_option("-r", "--recursive", action="store_true", default=False,
            help="Strip prefix from repos path")
    parser.add_option("--try", action="store_true", dest="tryflag", default=False,
            help="Do not sync repositories, only print what would be done")
    (opts, args) = parser.parse_args()
    def out(err):
        parser.print_help()
        parser.error(err)

    if len(args) < 2:
        out("Please give a action")
    src = args[0]
    cmd = args[1]
    if not os.path.exists(src):
        out("Source does not exist: " + src)
    if not cmdlist.has_key(cmd):
        out("Invalied action given: " + cmd)
    ret = run(src, cmdlist[cmd][0], args[2:], opts)
    if not ret:
        sys.exit(1)

# vim: foldmethod=marker
