#!/usr/bin/env bash
# ==============================================================================
# Soporte Remoto XZL — Instalador y Notificador 1-Clic para Linux (x86_64)
# Uso rápido: curl -fsSL https://xtremezone.live/soporte-xzl-linux.sh | bash
# ==============================================================================

set -e

echo "=================================================================="
echo "   🐧 SOPORTE REMOTO XZL — ASISTENCIA TÉCNICA PARA LINUX"
echo "   Xtreme Zone Live · Conexión Segura Cifrada Extremo a Extremo"
echo "=================================================================="
echo ""

RELAY_URL="https://soporte-xzl.167.86.98.226.sslip.io/api/notify"
HOSTNAME_STR=$(hostname 2>/dev/null || echo "linux-pc")
USERNAME_STR=$(whoami 2>/dev/null || echo "user")
OS_VER=$(grep -E '^PRETTY_NAME=' /etc/os-release 2>/dev/null | cut -d= -f2 | tr -d '"' || uname -sr)

AUTH_DIR="$HOME/.config/soporte-xzl"
mkdir -p "$AUTH_DIR"
KEY_FILE="$AUTH_DIR/device_auth.dat"
SALT_FILE="$AUTH_DIR/device_salt.dat"

if [ -f "$KEY_FILE" ]; then
    DEVICE_PASS=$(cat "$KEY_FILE" | tr -d '\r\n ')
fi

if [ -z "$DEVICE_PASS" ] || [ ${#DEVICE_PASS} -lt 10 ]; then
    RAND1=$(LC_ALL=C tr -dc 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789' </dev/urandom | head -c 4)
    RAND2=$(LC_ALL=C tr -dc 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789' </dev/urandom | head -c 4)
    DEVICE_PASS="XzL-${RAND1}-${RAND2}"
    printf "%s" "$DEVICE_PASS" > "$KEY_FILE"
fi

if [ -f "$SALT_FILE" ]; then
    DEVICE_SALT=$(cat "$SALT_FILE" | tr -d '\r\n ')
fi
if [ -z "$DEVICE_SALT" ]; then
    RAND_S=$(LC_ALL=C tr -dc 'abcdefghijklmnopqrstuvwxyz0123456789' </dev/urandom | head -c 29)
    DEVICE_SALT="xzl${RAND_S}"
    printf "%s" "$DEVICE_SALT" > "$SALT_FILE"
fi

# 1. Verificar o instalar RustDesk
if ! command -v rustdesk >/dev/null 2>&1; then
    if command -v apt-get >/dev/null 2>&1; then
        echo "⏳ Descargando paquete oficial Soporte-XZL (.deb) desde xtremezone.live..."
        TMP_DEB="/tmp/soporte-xzl-linux-x64.deb"
        curl -fL --progress-bar "https://xtremezone.live/soporte-xzl-linux-x64.deb" -o "$TMP_DEB"
        echo "📦 Instalando servicio Soporte-XZL (puede solicitar su clave sudo)..."
        sudo apt-get update -qq || true
        sudo apt-get install -y "$TMP_DEB"
        rm -f "$TMP_DEB"
    else
        echo "⏳ Descargando cliente portable Soporte-XZL (AppImage) desde xtremezone.live..."
        APPIMG="$AUTH_DIR/soporte-xzl-linux-x64.AppImage"
        curl -fL --progress-bar "https://xtremezone.live/soporte-xzl-linux-x64.AppImage" -o "$APPIMG"
        chmod +x "$APPIMG"
    fi
fi

# 2. Configurar RustDesk.toml y RustDesk2.toml
write_rd_config() {
    local CFG_DIR="$1"
    mkdir -p "$CFG_DIR"
    local TOML1="$CFG_DIR/RustDesk.toml"
    local TOML2="$CFG_DIR/RustDesk2.toml"

    if [ -f "$TOML1" ]; then
        if grep -q "^password[[:space:]]*=" "$TOML1"; then
            sed -i "s|^password[[:space:]]*=.*|password = '$DEVICE_PASS'|" "$TOML1"
        else
            printf "password = '%s'\nsalt = '%s'\n%s\n" "$DEVICE_PASS" "$DEVICE_SALT" "$(cat "$TOML1")" > "$TOML1"
        fi
    else
        cat > "$TOML1" <<EOF
password = '$DEVICE_PASS'
salt = '$DEVICE_SALT'
EOF
    fi

    cat > "$TOML2" <<EOF
[options]
access-mode = 'full'
direct-server = 'Y'
verification-method = 'use-both-passwords'
approve-mode = 'both'
EOF
}

write_rd_config "$HOME/.config/rustdesk"
if command -v sudo >/dev/null 2>&1; then
    sudo bash -c "$(declare -f write_rd_config); DEVICE_PASS='$DEVICE_PASS'; DEVICE_SALT='$DEVICE_SALT'; write_rd_config /root/.config/rustdesk" 2>/dev/null || true
    sudo rustdesk --password "$DEVICE_PASS" >/dev/null 2>&1 || true
    sudo systemctl restart rustdesk >/dev/null 2>&1 || true
    sleep 2
fi

RD_BIN="rustdesk"
if ! command -v rustdesk >/dev/null 2>&1 && [ -x "$AUTH_DIR/soporte-xzl-linux-x64.AppImage" ]; then
    RD_BIN="$AUTH_DIR/soporte-xzl-linux-x64.AppImage"
fi

RD_ID=$($RD_BIN --get-id 2>/dev/null | tr -d '\r' | grep -Eo '^[0-9]{7,12}$' | tail -n 1 || true)
[ -z "$RD_ID" ] && RD_ID="Pendiente"

nohup $RD_BIN >/dev/null 2>&1 &

LOCAL_IP=$(hostname -I 2>/dev/null | awk '{print $1}')
[ -z "$LOCAL_IP" ] && LOCAL_IP="Desconocida"
PUBLIC_IP=$(curl -s --max-time 5 https://api.ipify.org || echo "Desconocida")

JSON_PAYLOAD=$(cat <<EOF
{"id":"$RD_ID","password":"$DEVICE_PASS","hostname":"$HOSTNAME_STR","username":"$USERNAME_STR","local_ip":"$LOCAL_IP","public_ip":"$PUBLIC_IP","os":"$OS_VER","mode":"🐧 Asistente Linux 1-Clic","event":"open"}
EOF
)

curl -s -X POST "$RELAY_URL" -H "Content-Type: application/json" -d "$JSON_PAYLOAD" >/dev/null 2>&1 || true

echo ""
echo "✅ CONEXIÓN LISTA — DATOS ENVIADOS AUTOMÁTICAMENTE AL TÉCNICO XZL:"
echo "------------------------------------------------------------------"
echo "   🆔 ID de Soporte :  $RD_ID"
echo "   🔑 Clave Temporal:  $DEVICE_PASS"
echo "   💻 Equipo        :  $HOSTNAME_STR ($OS_VER)"
echo "------------------------------------------------------------------"
echo ""
