#!/usr/bin/env bash
# ==============================================================================
# BySAD Workstation VPS - Instalador de Escritorio XFCE + VNC + VS Code
# ==============================================================================
set -Eeuo pipefail

if [[ $EUID -ne 0 ]]; then
   echo "❌ Este script debe ejecutarse con privilegios de root (ej: sudo bash setup_vps_desktop.sh)"
   exit 1
fi

TARGET_USER="alesnecocell"
if ! id "${TARGET_USER}" >/dev/null 2>&1; then
    if [[ -n "${SUDO_USER:-}" && "${SUDO_USER}" != "root" ]]; then
        TARGET_USER="${SUDO_USER}"
    elif id "bysaddev" >/dev/null 2>&1; then
        TARGET_USER="bysaddev"
    else
        TARGET_USER="root"
    fi
fi

USER_HOME="$(eval echo ~${TARGET_USER})"
VNC_PASS="pokemon12"

echo "=========================================================="
echo "  Configurando Entorno Gráfico BySAD en VPS (${TARGET_USER})"
echo "=========================================================="

export DEBIAN_FRONTEND=noninteractive

echo "==> 1. Actualizando repositorios e instalando XFCE4 y VNC Server..."
apt-get update -y
apt-get install -y --no-install-recommends \
    xfce4 \
    xfce4-terminal \
    xfce4-session \
    xfce4-panel \
    xfdesktop4 \
    xfwm4 \
    dbus-x11 \
    x11-xserver-utils \
    tigervnc-standalone-server \
    tigervnc-common \
    tigervnc-tools \
    tightvncpasswd \
    curl \
    wget \
    gpg \
    apt-transport-https \
    git \
    ufw

echo "==> 2. Instalando Visual Studio Code oficial de Microsoft..."
install -m 0755 -d /etc/apt/keyrings
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor -o /etc/apt/keyrings/packages.microsoft.gpg --yes
chmod a+r /etc/apt/keyrings/packages.microsoft.gpg
echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list
apt-get update -y
apt-get install -y code

echo "==> 3. Configurando XStartup y VNC para el usuario ${TARGET_USER}..."
mkdir -p "${USER_HOME}/.vnc"
cat > "${USER_HOME}/.vnc/xstartup" << 'EOF'
#!/bin/sh
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
export XKL_XMODMAP_DISABLE=1
export XDG_CURRENT_DESKTOP="XFCE"
export DESKTOP_SESSION="xfce"
exec startxfce4
EOF
chmod +x "${USER_HOME}/.vnc/xstartup"

cat > "${USER_HOME}/.vnc/config" << 'EOF'
session=xfce
geometry=1920x1080
localhost=no
alwaysshared
EOF

# Configurar contraseña de VNC
if command -v vncpasswd >/dev/null 2>&1; then
    echo "${VNC_PASS}" | vncpasswd -f > "${USER_HOME}/.vnc/passwd"
else
    # Fallback binario para el hash DES RFB de 8 bytes
    python3 -c "
import struct
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = ('${VNC_PASS}' + '\0'*8)[:8].encode('latin1')
rev_key = bytes(int('{:08b}'.format(b)[::-1], 2) for b in key)
with open('${USER_HOME}/.vnc/passwd', 'wb') as f:
    c = Cipher(algorithms.TripleDES(rev_key * 3), modes.ECB()).encryptor()
    f.write(c.update(b'\0'*8) + c.finalize())
" 2>/dev/null || true
fi

chmod 600 "${USER_HOME}/.vnc/passwd"
chown -R "${TARGET_USER}:${TARGET_USER}" "${USER_HOME}/.vnc"

echo "==> 4. Creando servicio Systemd para inicio automático (vncserver.service)..."
cat > /etc/systemd/system/vncserver.service << EOF
[Unit]
Description=BySAD VNC Remote Desktop Server
After=syslog.target network.target

[Service]
Type=simple
User=${TARGET_USER}
Group=${TARGET_USER}
WorkingDirectory=${USER_HOME}
Environment=HOME=${USER_HOME}
ExecStartPre=-/usr/bin/vncserver -kill :1
ExecStart=/usr/bin/vncserver -fg -localhost no -rfbport 5900 :1
ExecStop=/usr/bin/vncserver -kill :1
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable vncserver.service
systemctl restart vncserver.service

echo "==> 5. Habilitando puertos en Firewall UFW..."
if command -v ufw >/dev/null 2>&1 && ufw status | grep -q "Status: active"; then
    ufw allow 5900:5902/tcp comment 'BySAD VNC Server'
    echo "✔ Puertos 5900-5902 permitidos en UFW firewall"
fi

echo "==> 6. Verificando puerto VNC 5900..."
sleep 3
if ss -tulpn | grep -q ":5900"; then
    echo "✔ Servidor VNC escuchando correctamente en 0.0.0.0:5900"
else
    echo "⚠ Revisando estado del servicio:"
    systemctl status vncserver.service --no-pager || true
fi

echo "=========================================================="
echo "✔ ¡Estación de Trabajo BySAD configurada exitosamente!"
echo "  - Usuario: ${TARGET_USER}"
echo "  - Resolución: 1920x1080 Full HD"
echo "  - Puerto VNC: 5900 (y display :1)"
echo "  - Contraseña VNC: ${VNC_PASS}"
echo "  - VS Code: Instalado y listo"
echo "=========================================================="
