import os
import subprocess
import sys
import SystemLib
import NetLib

#!/usr/bin/env python3

"""
installOfflineMode
Prepara el equipo cliente para el modo offline.

@exception OG_ERR_NOTFOUND Fichero o dispositivo no encontrado.
@exception OG_ERR_NOTCACHE No existe cache.
@author  Irina Gomez. ETSII. Universidad de Sevilla
@date    2013/12/5
"""


PROG = os.path.basename(__file__)

if len(sys.argv) > 1 and sys.argv[1] == "help":
    SystemLib.ogHelp()

SystemLib.ogEcho("log", "session $MSG_HELP_installOfflineMode")

# Cargamos las variables de entorno.
OGENGINECONFIGURATE = os.getenv('OGENGINECONFIGURATE')
if not OGENGINECONFIGURATE:
    exec(open('/opt/opengnsys/etc/engine.cfg').read())

DIRTFTP = "/opt/oglive/tftpboot"
DIROGCLIENT = os.path.join(DIRTFTP, "ogclient")

# Comprobamos que el DIROGCLIENT esta montado desde repo
repo_ip = NetLib.ogGetRepoIp()
result = subprocess.run(['df'], capture_output=True, text=True)
if f"{repo_ip} {DIRTFTP}" not in result.stdout:
    SystemLib.ogRaiseError("OG_ERR_NOTFOUND", "REPO OGclient")

# Copiamos el kernel y el initrd.
SystemLib.ogEcho("log", "session [10] updateBootCache")
if not update_boot_cache():
    SystemLib.ogRaiseError("OG_ERR_NOTCACHE", "")

# Creamos los dir necesarios.
OGCAC = "/path/to/ogcac"  # Placeholder for OGCAC path
SystemLib.ogEcho("log", f"session [40] mkdir -p {OGCAC}/{{ogclient, menus, log}}.")
os.makedirs(os.path.join(OGCAC, "menus/images/iconos"), exist_ok=True)
os.makedirs(os.path.join(OGCAC, "ogclient"), exist_ok=True)
os.makedirs(os.path.join(OGCAC, "log"), exist_ok=True)
os.makedirs(os.path.join(OGCAC, "opt/opengnsys/images"), exist_ok=True)

# Comparamos el cliente en el server y en cache
SystemLib.ogEcho("log", f"session [60] cp {DIROGCLIENT}/ogclient.sqfs {OGCAC}/ogclient/")
try:
    with open(os.path.join(DIROGCLIENT, "ogclient.sqfs.sum"), 'r') as f:
        SERVEROGCLIENT = f.read().strip()
except FileNotFoundError:
    SERVEROGCLIENT = None

try:
    with open(os.path.join(OGCAC, "ogclient/ogclient.sqfs.sum"), 'r') as f:
        CACHEOGCLIENT = f.read().strip()
except FileNotFoundError:
    CACHEOGCLIENT = None

if CACHEOGCLIENT != SERVEROGCLIENT:
    subprocess.run(['cp', os.path.join(DIROGCLIENT, "ogclient.sqfs"), os.path.join(OGCAC, "ogclient/")])
    subprocess.run(['cp', os.path.join(DIROGCLIENT, "ogclient.sqfs.sum"), os.path.join(OGCAC, "ogclient/")])

# Si se ha generado el menu de inicio lo copiamos a cache.
IPCLIENT = NetLib.ogGetIpAddress()
MENU = os.path.join("/path/to/oglog", f"{IPCLIENT}.info.html")  # Placeholder for OGLOG path
ICONO = "images/iconos/logoopengnsys.png"
if not os.path.isfile(MENU):
    generate_menu_default()

SystemLib.ogEcho("log", f"session [90] cp {MENU} {OGCAC}/menus/{IPCLIENT}.html")
subprocess.run(['cp', MENU, os.path.join(OGCAC, f"menus/{IPCLIENT}.html")])
subprocess.run(['sed', '-i', 's/"../images"/"images"/g', os.path.join(OGCAC, f"menus/{IPCLIENT}.html")])
subprocess.run(['wget', '--no-check-certificate', f"https://{NetLib.ogGetRepoIp()}/opengnsys/{ICONO}", '-O', os.path.join(OGCAC, f"menus/{ICONO}")])
