#!/usr/bin/python3

#
# This file is a part of the NsCDE - Not so Common Desktop Environment
# Author: Hegel3DReloaded
# Licence: GPLv3
#

import configparser, getopt, os, sys, re

def usage():
    print ("confget [ -c <file> [ -s <section> ] -k <key> [ -h ]")

def cmdoptions():
    section = ''
    typecf = ''

    try:
        opts, args = getopt.getopt(sys.argv[1:], "c:s:k:K:d:D:h", ["conffile=", "section=", "key=", "keys=", "defopt=", "delim=", "help"])
    except getopt.GetoptError as err:
        print(err)
        sys.exit(2)
    output = None
    verbose = False
    multi_concat = 0
    defopt=0
    delim='\n'
    for o, a in opts:
        if o in ("-c", "--conffile"):
            conffile = a
        elif o in ("-s", "--section"):
            section = a
        elif o in ("-k", "--key"):
            key = a
        elif o in ("-K", "--keys"):
            key = a
            multi_concat = 1
        elif o in ("-D", "--defopt"):
            defopt = a
        elif o in ("-d", "--delim"):
            delim = a
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        else:
            assert False, "getopt: unhandled option"

    return conffile, section, key, multi_concat, defopt, delim

def main ():
    conffile, section, key, multi_concat, defopt, delim = cmdoptions()

    parser = configparser.ConfigParser()
    parser.optionxform = lambda option: option
    parser.read(conffile)

    try:
        if multi_concat:
            keys = (key.split(","))
            for kk in keys:
                try:
                    print (parser.get(section, kk), end=delim)
                except configparser.NoOptionError:
                    print (defopt, end=delim)
            if delim != '\n':
                print ("")
        else:
            print (parser.get(section, key))
    except configparser.NoSectionError:
        sys.exit(2)
    except configparser.NoOptionError:
        sys.exit(3)

# Action ...
if __name__ == '__main__':
    cmdoptions()
    main()

