#!/usr/bin/env python3

import os
import subprocess

# generateMenuDefault - Crea fichero con la página web de inicio del cliente
#			con información de red y de los sistemas operativos instalados,
#			crea fichero con información del contenido de la caché local.


DEVICE = os.getenv('DEVICE', 'eth0')
with open(f'/tmp/net-{DEVICE}.conf') as f:
    exec(f.read())

FILEINFOHTML = f"{os.getenv('OGLOG')}/{subprocess.getoutput('ogGetIpAddress')}.info.html"
FILEINFOCACHE = f"{os.getenv('OGLOG')}/{subprocess.getoutput('ogGetIpAddress')}.cache.txt"
subprocess.run(['ogMountCache'], stderr=subprocess.DEVNULL)
CACHECONTENIDO = f"ls -m {os.getenv('OGCAC')}/{os.getenv('OGIMG')} 2>/dev/null"

SPEED = subprocess.getoutput(f"LANG=C ethtool {DEVICE} 2>/dev/null | awk '$1~/Speed/ {{print $2}}'")
SPEED = SPEED.lower()
if SPEED == "1000mb/s":
    pass
elif SPEED == "100mb/s":
    SPEED = f"<font color=\"blue\">{SPEED}</font>"
elif SPEED == "10mb/s":
    SPEED = f"<font color=\"grey\">{SPEED}</font>"
else:
    SPEED = f"<font color=\"red\">{SPEED}</font>"

DUPLEX = subprocess.getoutput(f"LANG=C ethtool {DEVICE} 2>/dev/null | awk '$1~/Duplex/ {{print $2}}'")
DUPLEX = DUPLEX.lower()
if DUPLEX == "full":
    pass
else:
    DUPLEX = f"<font color=\"red\">{DUPLEX}</font>"

CACHESIZEFREE = int(subprocess.getoutput('ogGetFreeSize $(ogFindCache)'))
with open(FILEINFOCACHE, 'w') as f:
    if CACHESIZEFREE == 0:
        f.write('0.MB,')
    else:
        f.write(f"{CACHESIZEFREE // 1024}.MB,")

# Crear menú por defecto.
with open(FILEINFOHTML, 'w') as f:
    f.write(f"""
<div align="center" style="font-family: Arial, Helvetica, sans-serif;">
<p style="color:#999999; font-size: 16px; margin: 2em;">

<table border="1" width="100%">
<tr>
<td rowspan="2"><p align="left"><img border="0" src="../images/iconos/logoopengnsys.png"><p> </td>
<td> {os.getenv('MSG_HOSTNAME')} </td> <td> {os.getenv('MSG_IPADDR')} </td> <td> {os.getenv('MSG_MACADDR')} </td> <td> {os.getenv('MSG_SPEED')} </td> <td> {os.getenv('MSG_DUPLEX')} </td> </tr>
<tr> <td>{os.getenv('HOSTNAME')} </td> <td> {subprocess.getoutput('ogGetIpAddress')} </td> <td> {subprocess.getoutput('ogGetMacAddress')} </td> <td> {SPEED} </td> <td> {DUPLEX} </td> </tr>
</table>
</p>

<h1>{os.getenv('MSG_MENUTITLE')}</h1>
""")

# Si existe el fichero de configuración creado por el script getConfiguration, ...
cfgfile = '/tmp/getconfig'
if os.path.isfile(cfgfile):
    # Tomar los datos del fichero.
    with open(cfgfile) as f_cfg, open(FILEINFOHTML, 'a') as f_html:
        for line in f_cfg:
            sep = line.split(';')
            for item in sep:
                dua = item.split(':')
                if len(dua) > 4 and dua[4] and dua[4] != "DATA":
                    f_html.write(f"<p><a href=\"command:bootOs {dua[0]} {dua[1]}\">{os.getenv('MSG_BOOT')} {dua[4]} ({dua[0]}, {dua[1]})</a></p>\n")
else:
    # Si no, obtener los datos de los discos.
    num_disks = int(subprocess.getoutput('ogDiskToDev | wc -w'))
    with open(FILEINFOHTML, 'a') as f_html:
        for d in range(1, num_disks + 1):
            num_partitions = int(subprocess.getoutput(f'ogGetPartitionsNumber {d}'))
            for p in range(1, num_partitions + 1):
                version = subprocess.getoutput(f'ogGetOsVersion {d} {p} 2>/dev/null').split(':')[1]
                if version:
                    f_html.write(f"<p><a href=\"command:bootOs {d} {p}\">{os.getenv('MSG_BOOT')} {version} ({d}, {p})</a></p>\n")

# Añadir opción de apagado.
with open(FILEINFOHTML, 'a') as f:
    f.write(f"""
<p><a href="command:poweroff">{os.getenv('MSG_POWEROFF')}</a></p>
</div>
""")

# Crear contenido de la caché.
with open(FILEINFOCACHE, 'a') as f:
    f.write(subprocess.getoutput(CACHECONTENIDO))
