#!/usr/bin/python3
# Proceso general de arranque de OpenGnsys Client.

import os
import re
import subprocess

import ogGlobals
from NetLib import ogGetIpAddress

ogstatus      = os.environ.get ('ogstatus', '')
ogcore        = os.environ.get ('ogcore', '')
oglog         = os.environ.get ('oglog', '')
oggroup       = os.environ.get ('OGGROUP', '')
ogactiveadmin = os.environ.get ('ogactiveadmin', '')
LANG          = os.environ.get ('LANG', 'es_ES')
LANG = LANG[0:LANG.index('_')]

LOGLEVEL=5

# Matando plymount para inicir browser o shell
subprocess.run (['pkill', '-9', 'plymouthd'])

# Arranque de OpenGnsys Client daemon (socket).
print (ogGlobals.lang.MSG_LAUNCHCLIENT)
# Indicar fichero de teclado de Qt para el idioma especificado (tipo "es.qmap").
if os.path.exists (f'/usr/local/etc/{LANG}.qmap'):
    os.environ['QWS_KEYBOARD'] = f'TTY:keymap=/usr/local/etc/{LANG}.qmap'

if os.path.exists ('/usr/share/OGAgent/opengnsys/linux/OGAgentService.py') and ogstatus != 'offline':
    os.chdir ('/usr/share/OGAgent')
    os.environ['OGAGENTCFG_OGCORE_IP']      = ogcore
    os.environ['OGAGENTCFG_OGLOG_IP']       = oglog
    os.environ['OGAGENTCFG_URLMENU_SCHEME'] = 'http'
    os.environ['OGAGENTCFG_URLMENU_IP']     = '127.0.0.1'
    os.environ['OGAGENTCFG_URLMENU_PORT']   = '81'
    subprocess.run (['python3', '-m', 'opengnsys.linux.OGAgentService', 'fg'])
else:
    ip = ogGetIpAddress()
    OGMENU = ''
    for FILE in [index, oggroup, ip]:
        if not FILE: continue
        m = f'{ogGlobals.OGCAC}/menus/{FILE}.html'
        if os.path.exists (m): OGMENU = m
    subprocess.run ([f'{ogGlobals.OPENGNSYS}/bin/launch_browser', m])

# Si fallo en cliente y modo "admin", cargar shell; si no, salir.
if ogactiveadmin == 'true':
    subprocess.run (['bash'])
