#!/bin/bash
# STA - Supporto Remoto (Linux)
# (c) 2026 Soluzioni Tecnologiche Avanzate srls - Tutti i diritti riservati
set -u

DEF_SERVER="soluzionitecnologicheavanzate.it"
DEF_KEY="OGy+2DgznR5bHOVWCSqWnrGCezDXoNUJkpqliTERELg="
VER_API="https://soluzionitecnologicheavanzate.it/api/data/rustdesk/version"
CFG_DIR="$HOME/.config/rustdesk"
APP="/tmp/STA-Assistenza-Linux.AppImage"

echo ""
echo "  ================================================"
echo "   STA - Supporto Remoto (Linux)"
echo "   Configurazione server in corso..."
echo "  ================================================"
echo ""

# Config letta dalla console admin (fallback ai valori predefiniti)
JSON="$(curl -fsSL --max-time 15 "$VER_API" 2>/dev/null)"
_getf(){ printf '%s' "$JSON" | sed -n "s/.*\"$1\"[ ]*:[ ]*\"\([^\"]*\)\".*/\1/p"; }
SERVER="$(_getf server)"; [ -z "${SERVER:-}" ] && SERVER="$DEF_SERVER"
KEY="$(_getf key)"; [ -z "${KEY:-}" ] && KEY="$DEF_KEY"
VER="$(_getf version)"; [ -z "${VER:-}" ] && VER="1.4.6"

# Configurazione server STA
mkdir -p "$CFG_DIR"
cat > "$CFG_DIR/RustDesk2.toml" <<EOF
rendezvous_server = "$SERVER"
nat_type = 1
serial = 0

[options]
custom-rendezvous-server = "$SERVER"
relay-server = "$SERVER"
api-server = "https://$SERVER"
key = "$KEY"
EOF
echo "[OK] Configurazione server STA applicata (server: $SERVER)."

ARCH="$(uname -m)"
case "$ARCH" in
  aarch64|arm64) A="aarch64" ;;
  *)             A="x86_64" ;;
esac
URL="https://github.com/rustdesk/rustdesk/releases/download/$VER/rustdesk-$VER-$A.AppImage"

echo "[..] Download RustDesk $VER ($A) in corso (attendere)..."
if ! curl -fL --max-time 120 -o "$APP" "$URL"; then
  echo ""
  echo "[ERRORE] Download fallito. Verifica la connessione internet."
  read -r -p "Premi INVIO per chiudere..."
  exit 1
fi
chmod +x "$APP"
echo "[OK] Client RustDesk $VER scaricato (versione allineata al server STA)."

echo "[..] Avvio RustDesk..."
"$APP" >/dev/null 2>&1 &
echo ""
echo "  ================================================"
echo "   Fatto! Comunica al tecnico il tuo ID"
echo "   e la password mostrati in RustDesk."
echo "  ================================================"
echo ""
