#!/bin/bash
set -euo pipefail

# ============================================================
# SPECHI CONSULTING - RustDesk Auto-Installer (macOS)
# Uso: curl -sSL https://soporte.spechi.mx/clients/instalar-spechi-mac.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 ""

# Detect architecture
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
    DMG_NAME="rustdesk-${RUSTDESK_VERSION}-aarch64.dmg"
else
    DMG_NAME="rustdesk-${RUSTDESK_VERSION}-x86_64.dmg"
fi

# Get public key
echo "[1/4] 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
echo "[2/4] Descargando RustDesk v${RUSTDESK_VERSION}..."
DMG_URL="https://github.com/rustdesk/rustdesk/releases/download/${RUSTDESK_VERSION}/${DMG_NAME}"
cd /tmp
curl -fsSL "$DMG_URL" -o rustdesk.dmg

# Install
echo "[3/4] Instalando..."
hdiutil attach rustdesk.dmg -quiet
cp -R "/Volumes/RustDesk/RustDesk.app" /Applications/ 2>/dev/null || true
hdiutil detach "/Volumes/RustDesk" -quiet 2>/dev/null || true
rm -f rustdesk.dmg

# Configure
echo "[4/4] Configurando servidor Spechi..."
CONFIG_DIR="$HOME/Library/Application Support/RustDesk/config"
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 desde Aplicaciones"
echo "  y comparte tu ID con Spechi Consulting"
echo ""
echo "  IMPORTANTE: Otorga permisos de"
echo "  Accesibilidad en Preferencias del Sistema"
echo "========================================="

open /Applications/RustDesk.app 2>/dev/null || true
