import ConfigParser, os

__version__ = "$Revision: 1.2 $"

def find_config(configname, appenv='', appdir=''):
    """Attempts to open configuration files in several way.

    This function attempts opening configuration files in three ways.
    Firstly it searches environment variable defined in appenv;
    a file named configname under the appenv directory becomes
    a candidate. Secondary, it look for configname under the user's
    home directory using HOME environment variable. Finally, the
    application's installation directory is looked in.
    If any of attempts is successful, it immediately returns
    a 2-tuple of the path found and the initialized ConfigParser
    object; otherwise, None is returned.
    """

    cp = ConfigParser.ConfigParser()

    # attempt to open APPENV-based path
    if appenv and os.environ.has_key(appenv):
        try:
            aepath = os.path.join(os.path.abspath(os.environ[appenv]),
                                  os.path.abspath(configname))
            cp.readfp(open(aepath, 'rw'))
        except:
            aepath = None
        if aepath:
            return (aepath, cp)

    # attempt to open HOME-based path
    if os.environ.has_key('HOME'):
        try:
            hmpath = os.path.join(os.path.abspath(os.environ['HOME']),
                                  os.path.abspath(configname))
            cp.readfp(open(hmpath, 'rw'))
        except:
            hmpath = None
        if hmpath:
            return (hmpath, cp)

    # attempt to open APPDIR-based path
    try:
        adpath = os.path.join(os.path.abspath(appdir),
                              os.path.abspath(configname))
        cp.read(open(adpath, 'rw'))
    except:
        adpath = None
    if adpath:
        return (adpath, cp)
        
    # every attempts have failed at this point.
    return None

