#!/usr/bin/env bash
# X64 LIOS Sunshine Game Streaming Launcher & Controller
# Optimizes uinput permissions, enables Avahi, provisions trusted localhost SAN SSL cert, and launches Web UI

set -e

# 1. Verificar si Sunshine está instalado
if ! command -v sunshine >/dev/null 2>&1; then
    if command -v notify-send >/dev/null 2>&1; then
        notify-send -u critical -i dialog-warning "X64 Sunshine" "Sunshine no está instalado. Puedes instalarlo con 1 clic desde el Centro Gaming de X64 Hello."
    fi
    exit 1
fi

# 2. Asegurar servicio Avahi para autodescubrimiento mDNS local con Moonlight
if ! systemctl is-active --quiet avahi-daemon.service 2>/dev/null; then
    sudo systemctl enable --now avahi-daemon.service 2>/dev/null || true
fi

# 3. Asegurar certificado TLS local con SAN (DNS:localhost, IP:127.0.0.1) y registrar confianza en navegador (NSS)
CRED_DIR="$HOME/.config/sunshine/credentials"
KEY_FILE="$CRED_DIR/cakey.pem"
CERT_FILE="$CRED_DIR/cacert.pem"
CERT_UPDATED=0

mkdir -p "$CRED_DIR"
if [ ! -s "$KEY_FILE" ]; then
    openssl genrsa -out "$KEY_FILE" 2048 >/dev/null 2>&1 || true
    chmod 600 "$KEY_FILE" 2>/dev/null || true
fi

if [ -s "$KEY_FILE" ]; then
    if [ ! -s "$CERT_FILE" ] || ! openssl x509 -in "$CERT_FILE" -noout -ext subjectAltName 2>/dev/null | grep -q "DNS:localhost"; then
        openssl req -new -x509 -days 365 -key "$KEY_FILE" -out "$CERT_FILE" \
            -subj "/CN=Sunshine Gamestream Host" \
            -addext "basicConstraints=critical,CA:TRUE" \
            -addext "keyUsage=critical,digitalSignature,keyEncipherment,keyCertSign" \
            -addext "extendedKeyUsage=serverAuth,clientAuth" \
            -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1" >/dev/null 2>&1 || true
        chmod 644 "$CERT_FILE" 2>/dev/null || true
        CERT_UPDATED=1
    fi
fi

if [ -s "$CERT_FILE" ] && command -v certutil >/dev/null 2>&1; then
    mkdir -p "$HOME/.pki/nssdb"
    if [ ! -f "$HOME/.pki/nssdb/cert9.db" ]; then
        certutil -d "sql:$HOME/.pki/nssdb" -N --empty-password >/dev/null 2>&1 || true
    fi
    if [ "$CERT_UPDATED" -eq 1 ]; then
        certutil -d "sql:$HOME/.pki/nssdb" -D -n "X64 Sunshine Localhost" >/dev/null 2>&1 || true
    fi
    if ! certutil -d "sql:$HOME/.pki/nssdb" -L -n "X64 Sunshine Localhost" >/dev/null 2>&1; then
        certutil -d "sql:$HOME/.pki/nssdb" -A -t "CT,C,C" -n "X64 Sunshine Localhost" -i "$CERT_FILE" >/dev/null 2>&1 || true
    fi
fi

# 4. Procesar banderas de control o inicialización
if [ "$1" = "--stop" ]; then
    systemctl --user stop app-dev.lizardbyte.app.Sunshine.service sunshine.service >/dev/null 2>&1 || true
    if command -v notify-send >/dev/null 2>&1; then
        notify-send -i dev.lizardbyte.app.Sunshine "X64 Sunshine Streaming" "Servidor de streaming detenido.\nMemoria RAM y codificadores liberados."
    fi
    exit 0
fi

if [ "$1" = "--setup-only" ]; then
    # Garantizar que el servicio permanezca desactivado al inicio del sistema (Zero-RAM on startup)
    systemctl --user disable app-dev.lizardbyte.app.Sunshine.service sunshine.service >/dev/null 2>&1 || true
    systemctl --user stop app-dev.lizardbyte.app.Sunshine.service sunshine.service >/dev/null 2>&1 || true
    exit 0
fi

# 5. Iniciar servicio de usuario de Sunshine bajo demanda (Zero-RAM on startup)
systemctl --user disable app-dev.lizardbyte.app.Sunshine.service sunshine.service >/dev/null 2>&1 || true

WAS_ALREADY_ACTIVE=0
if systemctl --user is-active --quiet app-dev.lizardbyte.app.Sunshine.service 2>/dev/null || systemctl --user is-active --quiet sunshine.service 2>/dev/null; then
    WAS_ALREADY_ACTIVE=1
    if [ "$CERT_UPDATED" -eq 1 ]; then
        systemctl --user restart app-dev.lizardbyte.app.Sunshine.service 2>/dev/null || systemctl --user restart sunshine.service 2>/dev/null || true
    fi
else
    systemctl --user daemon-reload
    systemctl --user start app-dev.lizardbyte.app.Sunshine.service 2>/dev/null || systemctl --user start sunshine.service 2>/dev/null || true
fi

# 6. Notificación amigable de inicio
if command -v notify-send >/dev/null 2>&1; then
    if [ "$WAS_ALREADY_ACTIVE" -eq 1 ]; then
        notify-send -i dev.lizardbyte.app.Sunshine "X64 Sunshine Streaming" "El servidor ya está en ejecución.\nAbriendo panel de control (https://localhost:47990)"
    else
        notify-send -i dev.lizardbyte.app.Sunshine "X64 Sunshine Streaming" "Servidor de streaming iniciado bajo demanda.\nAbriendo panel de control (https://localhost:47990)"
    fi
fi

# 7. Abrir panel de control Web para emparejamiento con Moonlight
sleep 1
if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "https://localhost:47990" 2>/dev/null || true
elif command -v chromium >/dev/null 2>&1; then
    chromium "https://localhost:47990" 2>/dev/null || true
fi
