import os
import subprocess

#!/usr/bin/env python3

# Idioma por defecto.
os.environ["LANG"] = os.getenv("LANG", "es_ES")
subprocess.run(["locale-gen", os.environ["LANG"]])

# Directorios del proyecto OpenGnsys.
os.environ["OPENGNSYS"] = os.getenv("OPENGNSYS", "/opt/opengnsys")
if os.path.isdir(os.environ["OPENGNSYS"]):
    os.environ["OGBIN"] = os.path.join(os.environ["OPENGNSYS"], "bin")
    os.environ["OGETC"] = os.path.join(os.environ["OPENGNSYS"], "etc")
    os.environ["OGLIB"] = os.path.join(os.environ["OPENGNSYS"], "lib")
    os.environ["OGAPI"] = os.path.join(os.environ["OGLIB"], "engine", "bin")
    os.environ["OGSCRIPTS"] = os.path.join(os.environ["OPENGNSYS"], "scripts")
    os.environ["OGIMG"] = os.path.join(os.environ["OPENGNSYS"], "images")
    os.environ["OGCAC"] = os.path.join(os.environ["OPENGNSYS"], "cache")
    os.environ["OGLOG"] = os.path.join(os.environ["OPENGNSYS"], "log")

    os.environ["PATH"] = os.pathsep.join([
        os.environ["PATH"],
        "/sbin",
        "/usr/sbin",
        "/usr/local/sbin",
        "/bin",
        "/usr/bin",
        "/usr/local/bin",
        "/opt/oglive/rootfs/opt/drbl/sbin",
        os.environ["OGSCRIPTS"],
        os.environ["OGAPI"],
        os.environ["OGBIN"]
    ])

    # Exportar parámetros del kernel.
    with open("/proc/cmdline") as f:
        for i in f.read().split():
            if "=" in i:
                key, value = i.split("=", 1)
                os.environ[key] = value

    # Cargar fichero de idioma.
    lang_file = os.path.join(os.environ["OGETC"], f"lang.{os.environ['LANG'].split('@')[0]}.conf")
    if os.path.isfile(lang_file):
        with open(lang_file) as f:
            for line in f:
                if "=" in line:
                    key, value = line.strip().split("=", 1)
                    os.environ[key] = value

    # Mensaje de carga del entorno.
    print(os.getenv("MSG_LOADAPI", "."))

    # Cargar mapa de teclado.
    subprocess.run(["loadkeys", os.environ["LANG"].split("_")[0]], stdout=subprocess.DEVNULL)

    # Cargar API de funciones.
    for lib_file in os.listdir(os.environ["OGAPI"]):
        if lib_file.endswith(".lib"):
            exec(open(os.path.join(os.environ["OGAPI"], lib_file)).read())

    # Cargar configuración del engine.
    engine_cfg = os.path.join(os.environ["OGETC"], "engine.cfg")
    if os.path.isfile(engine_cfg):
        exec(open(engine_cfg).read())
    os.environ["OGLOGCOMMAND"] = os.getenv("OGLOGCOMMAND", "/tmp/command.log")
    os.environ["OGLOGSESSION"] = os.getenv("OGLOGSESSION", "/tmp/session.log")

    # Cargar las APIs según engine.
    ogengine = os.getenv("ogengine")
    if ogengine:
        for api_file in os.listdir(os.environ["OGAPI"]):
            if api_file.endswith(f".{ogengine}"):
                exec(open(os.path.join(os.environ["OGAPI"], api_file)).read())

    # Configuración de la red (modo offline).
    initrd_cfg = "/tmp/initrd.cfg"
    if os.path.isfile(initrd_cfg):
        with open(initrd_cfg) as f:
            for line in f:
                if line.startswith("DEVICECFG="):
                    device_cfg = line.strip().split("=", 1)[1]
                    os.environ["DEVICECFG"] = device_cfg
                    if os.path.isfile(device_cfg):
                        exec(open(device_cfg).read())

    # FIXME Pruebas para grupos de ordenadores
    os.environ["OGGROUP"] = os.getenv("group", "")

    root_repo = os.getenv("ROOTREPO", os.getenv("OGSERVERIMAGES"))

    # Fichero de registros.
    og_log_file = os.path.join(os.environ["OGLOG"], f"{ogGetIpAddress()}.log")
    os.environ["OGLOGFILE"] = og_log_file

# Compatibilidad para usar proxy en clientes ogLive.
if not os.getenv("http_proxy") and os.getenv("ogproxy"):
    os.environ["http_proxy"] = os.getenv("ogproxy")

# Compatibilidad para usar servidor DNS en clientes ogLive.
if not os.path.isfile("/run/resolvconf/resolv.conf") and os.getenv("ogdns"):
    os.makedirs("/run/resolvconf", exist_ok=True)
    with open("/run/resolvconf/resolv.conf", "w") as f:
        f.write(f"nameserver {os.getenv('ogdns')}\n")

# Declaración de códigos de error.
error_codes = {
    "OG_ERR_FORMAT": 1,
    "OG_ERR_NOTFOUND": 2,
    "OG_ERR_PARTITION": 3,
    "OG_ERR_LOCKED": 4,
    "OG_ERR_IMAGE": 5,
    "OG_ERR_NOTOS": 6,
    "OG_ERR_NOTEXEC": 7,
    "OG_ERR_NOTWRITE": 14,
    "OG_ERR_NOTCACHE": 15,
    "OG_ERR_CACHESIZE": 16,
    "OG_ERR_REDUCEFS": 17,
    "OG_ERR_EXTENDFS": 18,
    "OG_ERR_OUTOFLIMIT": 19,
    "OG_ERR_FILESYS": 20,
    "OG_ERR_CACHE": 21,
    "OG_ERR_NOGPT": 22,
    "OG_ERR_REPO": 23,
    "OG_ERR_NOMSDOS": 24,
    "OG_ERR_IMGSIZEPARTITION": 30,
    "OG_ERR_UPDATECACHE": 31,
    "OG_ERR_DONTFORMAT": 32,
    "OG_ERR_IMAGEFILE": 33,
    "OG_ERR_GENERIC": 40,
    "OG_ERR_UCASTSYNTAXT": 50,
    "OG_ERR_UCASTSENDPARTITION": 51,
    "OG_ERR_UCASTSENDFILE": 52,
    "OG_ERR_UCASTRECEIVERPARTITION": 53,
    "OG_ERR_UCASTRECEIVERFILE": 54,
    "OG_ERR_MCASTSYNTAXT": 55,
    "OG_ERR_MCASTSENDFILE": 56,
    "OG_ERR_MCASTRECEIVERFILE": 57,
    "OG_ERR_MCASTSENDPARTITION": 58,
    "OG_ERR_MCASTRECEIVERPARTITION": 59,
    "OG_ERR_PROTOCOLJOINMASTER": 60,
    "OG_ERR_DONTMOUNT_IMAGE": 70,
    "OG_ERR_DONTSYNC_IMAGE": 71,
    "OG_ERR_DONTUNMOUNT_IMAGE": 72,
    "OG_ERR_NOTDIFFERENT": 73,
    "OG_ERR_SYNCHRONIZING": 74,
    "OG_ERR_NOTUEFI": 80,
    "OG_ERR_NOTBIOS": 81
}

for key, value in error_codes.items():
    os.environ[key] = str(value)