#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import subprocess

from hga.controlgrupos.cliente.appcorealumno import AppCoreAlumno
from hga.appcore import AppCore
from hga.controlgrupos.common.srunningcontrol import SRunningControl
from hga.controlgrupos.cliente.settingscliente import PID_FILE
from hga.controlgrupos.cliente.settingscliente import GUI_CLIENTE

# ======================================================
# Rutas de certificados
# ======================================================
CERT_DIR = os.path.expanduser("~/.local/share/gnome-remote-desktop")
CERT_FILE = os.path.join(CERT_DIR, "tls-hgr.crt")
KEY_FILE = os.path.join(CERT_DIR, "tls-hgr.key")

# ======================================================
# Función para generar certificado TLS si no existe
# ======================================================
def generar_certificado_tls():
    try:
        # Crear carpeta si no existe
        os.makedirs(CERT_DIR, exist_ok=True)

        # Generar certificado si faltan archivos
        if not (os.path.exists(CERT_FILE) and os.path.exists(KEY_FILE)):
            subprocess.run([
                "openssl", "req", "-new", "-newkey", "rsa:4096",
                "-days", "36500", "-nodes", "-x509",
                "-subj", "/C=SE/ST=NONE/L=NONE/O=GNOME/CN=gnome.org",
                "-out", CERT_FILE,
                "-keyout", KEY_FILE
            ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        else:
            # No hacer nada si ya existen
            pass
    except Exception as e:
        print(f"Error al generar el certificado TLS: {e}")

# ======================================================
# Flujo principal
# ======================================================
# 🔧 Generar certificado antes de iniciar el cliente
generar_certificado_tls()

# Comprueba si se está ejecutando HGA.
s = SRunningControl(PID_FILE)
if not s.is_running():
    s.create()
    hga = AppCore(GUI_CLIENTE)
    hga.iniciar_cliente()
    s.remove()
else:
    print("Ya hay una instancia de HGR cliente en ejecución")
