#!/usr/bin/python
########################################################################
### FILE:	greylist-config
### PURPOSE:	Set/get items in greylistd configuration file
########################################################################


### Define values not yet availble in Python 2.1
False, True = (1 is 0), (1 is 1)


### File paths
defFile  = "/etc/default/greylist"
confFile = "/etc/greylistd/config"

defLines  = []
confLines = []


def readLines (filename):
    try:
        fp = open(filename)
        lines = fp.readlines(True)
        fp.close()
    except IOError, e:
        stderr.write("Cannot read from %s: %s\n"%(filename, e[1]))
        exit(-1)

    return lines


def writeLines (filename, lines):
    try:
        fp = open(filename, "w")
        fp.writelines(lines)
        fp.close()

    except IOError:
        stderr.write("Cannot write to %s: %s\n"%(filename, e[1]))
        exit(-1)

    

def listSections ():
    
    
    

def valueList ():
    values = []
    for section in confParser.sections:
        values.append("  Section \"%s\" options:\n"%section)
        for option in confParser.options(section):
            values.append("    \"%s\"\n"%option)

    return values


def usage (progname, message=None):
    if message:
        out = stderr
        out.write("%s: %s\n\n"%(progname, message))
    else:
        out = stdout
        out.write("Configuration tool for greylistd\n\n")

        
    out.write("\n".join([
        "Usage: %s -help"%progname,
        "       %s [<section> [<option> [<value>]]]"%progname,
        "",
        "where:",
        "   <section> is \"default\" or a section in the configuration file.",
        "        If not provided, a list of available sections is printed.",
        "   <option> is one of the options in the given section.",
        "        If not provided, list available options within the section.",
        "   <value> is the new setting for the given option.",
        "        If not provided, the current setting is shown.",
        "",
        ""]))

    exit((-1, 0)[not message])




progname = None
section  = None
option   = None
value    = None

for arg in argv:
    if progname is None:
        progname = arg.split("/")[-1]

    elif arg.startswith("-"):
        option = arg.lstrip("-")
        if option == "help":
            usage()

        else:
            usage("Invalid option: '%s'"%arg)

    elif section is None:
        section = arg

    elif option = None:
        option = arg

    elif value is None:
        value = arg

    else:
        usage("Too many arguments")


if section is None:
    s = listSections()

elif option is None:
    s = listOptions(section)

elif value is None:
    s = showValue(section, option)

else:
    s = setValue(section, option, value)

exit((0, -1)[not s])

