#!/bin/bash
set -euo pipefail

# ============================================================
# SPECHI CONSULTING - RustDesk Auto-Installer (Linux)
# Uso: curl -sSL https://soporte.spechi.mx/clients/instalar-spechi-linux.sh | bash
# ============================================================

SERVER_ID="soporte.spechi.mx"
SERVER_RELAY="soporte.spechi.mx"
SERVER_API="https://soporte.spechi.mx"
KEY_URL="https://soporte.spechi.mx/api/rustdesk/key"
RUSTDESK_VERSION="1.3.7"

echo ""
echo "========================================="
echo "  Spechi Consulting - Soporte Remoto"
echo "  Instalador automático de RustDesk"
echo "========================================="
echo ""

# Get public key
echo "[1/3] Obteniendo clave del servidor..."
PUB_KEY=$(curl -sf "$KEY_URL" | python3 -c "import sys,json; print(json.load(sys.stdin).get('key',''))" 2>/dev/null || echo "")

# Download and install
echo "[2/3] Descargando RustDesk v${RUSTDESK_VERSION}..."
ARCH=$(dpkg --print-architecture 2>/dev/null || echo "amd64")
DEB_URL="https://github.com/rustdesk/rustdesk/releases/download/${RUSTDESK_VERSION}/rustdesk-${RUSTDESK_VERSION}-${ARCH}.deb"

cd /tmp
wget -q "$DEB_URL" -O rustdesk.deb
sudo dpkg -i rustdesk.deb || sudo apt-get install -f -y
rm -f rustdesk.deb

# Configure
echo "[3/3] Configurando servidor Spechi..."
CONFIG_DIR="$HOME/.config/rustdesk"
mkdir -p "$CONFIG_DIR"

cat > "$CONFIG_DIR/RustDesk2.toml" <<EOF
rendezvous_server = '${SERVER_ID}'
nat_type = 1
serial = 0

[options]
custom-rendezvous-server = '${SERVER_ID}'
relay-server = '${SERVER_RELAY}'
api-server = '${SERVER_API}'
key = '${PUB_KEY}'
EOF

echo ""
echo "========================================="
echo "  INSTALACIÓN COMPLETA"
echo "  Abre RustDesk y comparte tu ID"
echo "  con el técnico de Spechi Consulting"
echo "========================================="
