import os, errno
from MailPing import fileutil

class NoSuchConfigItem(Exception):
    """Configuration item does not exist."""

class _NoDefault:
    pass

def getTime(configdir, name, default=_NoDefault):
    t = fileutil.getTime(os.path.join(configdir, name))
    if t < 0:
        if default is _NoDefault:
            raise NoSuchConfigItem, name
        else:
            t = default
    return t

def getEmail(configdir, name, default=_NoDefault):
    path = os.path.join(configdir, name)
    try:
        f=file(path)
    except IOError, e:
        if e.errno == errno.ENOENT:
            if default is _NoDefault:
                raise NoSuchConfigItem, name
            else:
                return default
        else:
            raise

    l=f.readline()
    l=l.strip()
    return l

DEFAULT_CONFIGDIR = '/etc/mailping'
DEFAULT_STATEDIR = '/var/lib/mailping'

def getConfigDir():
    return os.environ.get('MAILPING_CONFIGDIR',
                          DEFAULT_CONFIGDIR)

def getStateDir():
    return os.environ.get('MAILPING_STATEDIR',
                          DEFAULT_STATEDIR)
