#!/usr/bin/env bash
set -euo pipefail
ID_SERVER='rd.nts.pf'
RELAY_SERVER='rd.nts.pf'
KEY='8yuSN4iR3+jraYZ72n71cT7d8TlxWbXl3nnhtjb2Bvs='
if [ "$(id -u)" -ne 0 ]; then echo "Lancez avec sudo: sudo bash install-linux.sh" >&2; exit 1; fi
api='https://api.github.com/repos/rustdesk/rustdesk/releases/latest'
json="$(curl -fsSL -H 'User-Agent: NTS-RustDesk-Installer' "$api")"
arch="$(uname -m)"
if command -v apt-get >/dev/null 2>&1; then
  pattern='x86_64.deb'; if [ "$arch" = 'aarch64' ] || [ "$arch" = 'arm64' ]; then pattern='aarch64.deb'; fi
  url="$(printf '%s' "$json" | python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(sys.stdin); print(next(a["browser_download_url"] for a in d["assets"] if a["name"].endswith(p)))' "$pattern")"
  tmp="/tmp/rustdesk-${pattern}"
  curl -fL "$url" -o "$tmp"
  apt-get update
  apt-get install -y "$tmp" || apt-get -f install -y
elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then
  pattern='x86_64.rpm'
  url="$(printf '%s' "$json" | python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(sys.stdin); print(next(a["browser_download_url"] for a in d["assets"] if a["name"].endswith(p)))' "$pattern")"
  tmp="/tmp/rustdesk-${pattern}"
  curl -fL "$url" -o "$tmp"
  if command -v dnf >/dev/null 2>&1; then dnf install -y "$tmp"; else yum install -y "$tmp"; fi
else
  echo "Distribution non supportée automatiquement. Téléchargez RustDesk puis lancez les commandes --option." >&2
  exit 1
fi
bin="$(command -v rustdesk || true)"; [ -n "$bin" ] || bin='/usr/bin/rustdesk'
"$bin" --option custom-rendezvous-server "$ID_SERVER"
"$bin" --option relay-server "$RELAY_SERVER"
"$bin" --option api-server ''
"$bin" --option key "$KEY"
echo "RustDesk configuré: ID=$ID_SERVER Relay=$RELAY_SERVER"
