#!/bin/bash
clear
echo "============================================================"
echo "  Installazione Assistenza Remota - Informatica Gelormini"
echo "============================================================"
echo ""

# Detect architecture
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
    URL="https://github.com/rustdesk/rustdesk/releases/download/1.4.6/rustdesk-1.4.6-aarch64.dmg"
else
    URL="https://github.com/rustdesk/rustdesk/releases/download/1.4.6/rustdesk-1.4.6-x86_64.dmg"
fi

TMPDIR=$(mktemp -d)
DMG="$TMPDIR/rustdesk.dmg"

echo "Scaricamento RustDesk in corso..."
curl -L -o "$DMG" "$URL"

if [ ! -f "$DMG" ]; then
    echo "ERRORE: Download fallito. Controlla la connessione internet."
    exit 1
fi

echo "Download completato."
echo ""
echo "Installazione in corso..."

# Mount and install
MOUNT=$(hdiutil attach "$DMG" -nobrowse | tail -1 | awk '{print $3}')
if [ -d "$MOUNT/RustDesk.app" ]; then
    cp -R "$MOUNT/RustDesk.app" /Applications/
    hdiutil detach "$MOUNT" -quiet
    echo "RustDesk installato in /Applications"
fi

echo ""
echo "Configurazione server assistenza..."

# Configure RustDesk - scrivi in entrambe le posizioni
CFG_CONTENT="rendezvous_server = 'informaticagelormini.ddns.net'
nat_type = 1
serial = 0

[options]
custom-rendezvous-server = 'informaticagelormini.ddns.net'
relay-server = 'informaticagelormini.ddns.net'
key = 'PEQMCbxAg6WVxPDEd7YN6emBoeekWLtBi7kAeKhLopU='
enable-audio = 'Y'"

# 1. Config utente
CFG_DIR="$HOME/Library/Preferences/com.rustdesk.RustDesk/config"
mkdir -p "$CFG_DIR"
echo "$CFG_CONTENT" > "$CFG_DIR/RustDesk2.toml"

# 2. Config root service (se presente)
if [ -d "/var/root/Library/Preferences" ]; then
    sudo mkdir -p "/var/root/Library/Preferences/com.rustdesk.RustDesk/config" 2>/dev/null
    echo "$CFG_CONTENT" | sudo tee "/var/root/Library/Preferences/com.rustdesk.RustDesk/config/RustDesk2.toml" >/dev/null 2>/dev/null
fi

# Kill and restart
killall RustDesk 2>/dev/null
sleep 2
open /Applications/RustDesk.app

# Cleanup
rm -rf "$TMPDIR"

echo ""
echo "============================================================"
echo ""
echo "  INSTALLAZIONE COMPLETATA!"
echo ""
echo "  RustDesk e stato installato e configurato automaticamente."
echo "  Comunica il tuo ID al tecnico per ricevere assistenza."
echo ""
echo "  Informatica Gelormini - Tel: 339 288 5800"
echo ""
echo "============================================================"
echo ""
read -p "Premi INVIO per chiudere..."
