#!/bin/bash
# ============================================================
# Instalador RustDesk preconfigurado - DAROSI Soporte Remoto
# Para macOS - Ejecutar en Terminal
# ============================================================

SERVER="soporte.darosi.com.mx"
KEY="vfZ9e9zmgIHJ59t19ng5AnPge1dDilg0wVT6Yv17XtI="

echo ""
echo "============================================"
echo "  DAROSI - Instalador de Soporte Remoto"
echo "============================================"
echo ""

# Detectar arquitectura
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
    URL="https://soporte.darosi.com.mx/descargas/clients/rustdesk-macos-apple.dmg"
    echo "[INFO] Detectado: Apple Silicon (M1/M2/M3/M4)"
else
    URL="https://soporte.darosi.com.mx/descargas/clients/rustdesk-macos-intel.dmg"
    echo "[INFO] Detectado: Intel"
fi

DMG="/tmp/rustdesk-darosi.dmg"

echo "[1/3] Descargando RustDesk..."
curl -sL "$URL" -o "$DMG"
echo "       Descarga completada."

echo "[2/3] Instalando RustDesk..."
MOUNT=$(hdiutil attach "$DMG" -nobrowse -quiet | tail -1 | awk '{print $3}')
cp -R "$MOUNT/RustDesk.app" /Applications/ 2>/dev/null || sudo cp -R "$MOUNT/RustDesk.app" /Applications/
hdiutil detach "$MOUNT" -quiet
rm -f "$DMG"
echo "       Instalación completada."

echo "[3/3] Configurando servidor DAROSI..."
CONFIG_DIR="$HOME/Library/Preferences/net.rustdesk.RustDesk/config"
mkdir -p "$CONFIG_DIR"
cat > "$CONFIG_DIR/RustDesk2.toml" << TOML
rendezvous_server = 'soporte.darosi.com.mx'
nat_type = 1
serial = 0

[options]
custom-rendezvous-server = '$SERVER'
relay-server = '$SERVER'
api-server = 'https://$SERVER'
key = '$KEY'
TOML
echo "       Servidor configurado: $SERVER"

echo ""
echo "============================================"
echo "  ¡Instalación completada!"
echo "  Servidor: $SERVER"
echo "============================================"
echo ""
echo "Abre RustDesk desde Aplicaciones y comparte"
echo "tu ID y contraseña con el técnico de DAROSI."
echo ""

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