import os
from calculate.utils.fs import readFile
from calculate.variables.datavars import Variable, Namespace, Dependence, \
    StringType, BooleanType, Calculate

def get_ebuild_phase():
    return os.environ.get("EBUILD_PHASE", "")

def get_chroot_status():
    """Detect chroot mode by different mountinfo"""
    pid = os.getpid()
    try:
        if not os.access('/proc/self/mountinfo', R_OK) or \
                not os.access('/proc/1/mountinfo', R_OK):
            return False
        infos = [readFile(x) for x in ('/proc/1/mountinfo',
                                       '/proc/self/mountinfo')]
        return infos[0] != infos[1]
    except Exception:
        return False

def is_system_boot():
    if os.readlink('/proc/self/fd/0') == '/dev/console':
        return True
    else:
        return False

Variable("ebuild_phase", type=StringType,
    source=Calculate(get_ebuild_phase))
Variable("chroot_status", type=BooleanType,
    source=Calculate(get_chroot_status))
Variable("system_boot_set", type=BooleanType,
    source=Calculate(is_system_boot))
