import os
from calculate.utils.fs import readFile
from calculate.variables.datavars import Variable, Namespace, Dependence, \
    StringType, BooleanType, HashType, 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))

# Переменная, в которую будут помещаться пути к текущим шаблонам.
Variable("current_template", type=StringType, source="")

class CmdlineParams(object):
    """
    Параметры опции загрузки ядра calculate=
    """
    # названия параметров
    Calculate = "calculate"
    IsoscanFile = "iso-scan/filename"
    IOScheduler = "elevator"

    # внутренние параметры calculate
    Locale = "lang"
    Keymap = "keymap"
    Timezone = "timezone"
    Resolution = "resolution"
    Video = "video"
    Composite = "composite"
    Domain = "domain"
    DomainPassword = "domain_pw"
    Audio = "audio"
    Clock = "clock"

def get_cmdline_parameter(paramname):
    cmdLine = "/proc/cmdline"
    for param in readFile(cmdLine).split(" "):
        parname, op, value = param.partition("=")
        if parname == paramname:
            return value
    return None

def get_calculate_cmdline():
    names = (
        CmdlineParams.Locale,
        CmdlineParams.Keymap,
        CmdlineParams.Timezone,
        CmdlineParams.Resolution,
        CmdlineParams.Video,
        CmdlineParams.Composite,
        CmdlineParams.Domain,
        CmdlineParams.DomainPassword,
        CmdlineParams.Audio,
        CmdlineParams.Clock)
    # try get timezone from kernel calculate param
    params = {x:"" for x in names}
    try:
        value = get_cmdline_parameter(CmdlineParams.Calculate)
        if value is not None:
            for cparam in (x for x in value.split(',') if x):
                k, v = cparam.partition(':')[0::2]
                if k and v and k in names:
                    params[k.strip()] = v.strip()
    except (IOError, ValueError, IndexError):
        pass
    return params

def get_isoscan_filename():
    value = get_cmdline_parameter(CmdlineParams.IsoscanFile)
    if value is not None:
        return value
    return ""

def get_isoscan_fullpath(base_path, filename):
    if filename:
        return os.path.join(base_path.value, filename.value.lstrip("/"))
    return ""

with Namespace('cmdline'):
    Variable("calculate", type=HashType.fixed,
        source=Calculate(get_calculate_cmdline))
    Variable("isoscan_filename", type=StringType,
        source=Calculate(get_isoscan_filename))

with Namespace('isoscan'):
    Variable("base_path", type=StringType,
        source="/run/initramfs/isoscan")
    Variable("full_path", type=StringType,
        source=Calculate(get_isoscan_fullpath,
            '.base_path', 'main.cl.cmdline.isoscan_filename'
        ))
