# -*- coding: utf-8 -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
import ulib.base.i_need_py23

__all__ = ('get_uinst', 'is_uinstdir', 'get_uinstdir', 'find_uinstdir')

from os import path

def get_uinst(p):
    if p is not None: return path.join(p, '.uinst.conf')
    else: return None

def is_uinstdir(p):
    return p is not None and path.isfile(get_uinst(p))

def get_uinstdir(p):
    if is_uinstdir(p): return p
    else: return None

def __validate(p, validator):
    if p in ('/', ''): return False
    elif validator is None: return True
    else: return validator(p)

def find_uinstdir(p, validator=None):
    if p is None: return None

    p = path.abspath(p)
    while __validate(p, validator):
        uinstdir = get_uinstdir(p)
        if uinstdir is not None: return uinstdir
        else: p = path.split(p)[0]
    return None
