
from configparser import ConfigParser, ExtendedInterpolation

from os import environ


def to_environ_key(key):
    return key.upper()


class EnvironmentConfigParser(ConfigParser):

    def has_option(self, section, option):
        if to_environ_key('_'.join((section, option))) in environ:
            return True
        return super(EnvironmentConfigParser, self).has_option(section, option)

    def get(self, section, option, **kwargs):
        key = to_environ_key('_'.join((section, option)))
        if key in environ:
            return environ[key]
        return super(EnvironmentConfigParser, self).get(section, option, **kwargs)


def readConfigFile(cfgfile):
    """
    Read config files and return ConfigParser object

    @param cfgfile: filename or array of filenames
    @return: ConfigParser object
    """
    parser = EnvironmentConfigParser(
        interpolation=ExtendedInterpolation(),
        converters={'list': lambda x: [i.strip() for i in x.split(',')]}
    )
    parser.read(cfgfile)
    return parser


def _config_files():
    # Import here (not at module top) to avoid any circular-import risk.
    from core.paths import workdir_path, bundled
    return [
        bundled('etc', 'honeypot.cfg.base'),	# bundled read-only defaults
        workdir_path('etc', 'honeypot.cfg'),	# site-local overrides
        workdir_path('honeypot.cfg'),		# convenience root-level override
    ]


CONFIG = readConfigFile(_config_files())
