#!/bin/bash
# Soporte remoto de Adandaa: instala RustDesk y lo conecta al servidor rs.adandaa.com.
# Adandaa remote support: installs RustDesk and points it to the rs.adandaa.com server.
# Uso / usage:  curl -fsSL https://rs.adandaa.com/descargas/soporte-adandaa-linux.sh | sudo bash
set -euo pipefail
VER=1.5.0
HOST=rs.adandaa.com
KEY='2cFIcs9H9rmzOT8HwAplHpWSNyZz876hD5W4K+kSzgE='
BASE="https://github.com/rustdesk/rustdesk/releases/download/$VER"

[ "$(id -u)" = 0 ] || { echo "Ejecute con sudo / run with sudo"; exit 1; }

# Deja la configuración del servidor en el RustDesk2.toml, conservando el resto de opciones.
escribir_config() {
  mkdir -p "$(dirname "$1")"; touch "$1"
  awk -v h="$HOST" -v k="$KEY" -v q="'" '
    function ours() { print "custom-rendezvous-server = " q h q; print "relay-server = " q h q; print "key = " q k q; print "api-server = " q q }
    /^(custom-rendezvous-server|relay-server|key|api-server|rendezvous_server) *=/ { next }
    /^\[options\]/ { print; ours(); done = 1; next }
    { print }
    END { if (!done) { print "[options]"; ours() } }' "$1" > "$1.tmp" && mv "$1.tmp" "$1"
}

case "$(uname -m)" in aarch64|arm64) A=aarch64 ;; *) A=x86_64 ;; esac
TMP=$(mktemp -d)
echo "Descargando e instalando RustDesk $VER / Downloading and installing RustDesk $VER ..."
if command -v apt-get >/dev/null; then
  curl -fL -o "$TMP/rustdesk.deb" "$BASE/rustdesk-$VER-$A.deb"
  apt-get install -y "$TMP/rustdesk.deb"
elif command -v zypper >/dev/null; then
  curl -fL -o "$TMP/rustdesk.rpm" "$BASE/rustdesk-$VER-0.$A-suse.rpm"
  zypper --non-interactive --no-gpg-checks install "$TMP/rustdesk.rpm"
elif command -v dnf >/dev/null || command -v yum >/dev/null; then
  curl -fL -o "$TMP/rustdesk.rpm" "$BASE/rustdesk-$VER-0.$A.rpm"
  "$(command -v dnf || command -v yum)" install -y "$TMP/rustdesk.rpm"
else
  echo "Distribución no soportada: use el AppImage de https://rs.adandaa.com / unsupported distro: use the AppImage"
  exit 1
fi
rm -rf "$TMP"

# El servicio corre como root; la ventana, como el usuario que pidió sudo.
systemctl stop rustdesk >/dev/null 2>&1 || true
escribir_config /root/.config/rustdesk/RustDesk2.toml
if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ]; then
  H=$(getent passwd "$SUDO_USER" | cut -d: -f6)
  escribir_config "$H/.config/rustdesk/RustDesk2.toml"
  chown -R "$SUDO_USER": "$H/.config/rustdesk"
fi
systemctl start rustdesk >/dev/null 2>&1 || true

echo
echo "Listo. Abra RustDesk y dele a soporte el ID y la contraseña. (Con Wayland, inicie sesión en Xorg si no se ve la pantalla.)"
echo "Done. Open RustDesk and give support the ID and password. (On Wayland, log in with Xorg if the screen is not shown.)"
