#!/usr/bin/python
#
# This cannot use interruptly.
# Will Called by debconf internally
#
# 2001 Takuo KITAME <kitame@debian.org>
# GPL2
#
# Usage: viewcvs-config -k keyname -v value

import getopt
import sys
import string
import re
import ConfigParser

def SetValue(contents, var, value):
    pattern = re.compile('^' + var + r'\s*=\s*.*$', re.MULTILINE)
    repl = '%s = %s' % (var, value)
    return re.sub(pattern, repl, contents)

if __name__ == "__main__":
    argv = sys.argv
    getting = 0
    all = 0
    section = "general"
    opts, args = getopt.getopt(argv[1:], 'k:v:g:s:a',
        ['key=', 'value=', 'get=', 'section=', 'all'])
    for opt, val in opts:
        if opt in ('-k', '--key'):
           key = val
        elif opt in ('-v', '--value'):
           value = val
        elif opt in ('-g', '--get'):
           getting = 1
           value = val
        elif opt in ('-s', '--section'):
           section = val
	elif opt in ('-a', '--all'):
           getting = 1
           all = 1

    if getting:
        parser = ConfigParser.ConfigParser()
        parser.read("/etc/viewcvs/viewcvs.conf")
        if all:
            for opt, val in parser.items(section):
                print opt + '=' + val    
        else:
            if parser.has_option(section, value):
                print parser.get(section, value)
        sys.exit(0)

    try:
        contents = open("/etc/viewcvs/viewcvs.conf", "r").read()
        try:
            open("/etc/viewcvs/viewcvs.conf.bak", "w").write(contents)
        except IOError, e:
            if e[0] == 13:
                # EACCES: permission denied
                Error("You do not have permission to write file /etc/viewcvs/viewcvs.conf.bak")
            Error("Unknown error writing file /etc/viewcvs/viewcvs.conf.bak", IOError, e)

    except IOError, e:
        Error(str(e))

    contents = SetValue(contents, key, value)

    try:
        open("/etc/viewcvs/viewcvs.conf", "w").write(contents)
    except IOError, e:
        if e[0] == 13:
            # EACCES: permission denied
            Error("You do not have permission to write file /etc/viewcvs/viewcvs.conf")
        Error("Unknown error writing file /etc/viewcvs/viewcvs.conf", IOError, e)
