#!/bin/bash
set -euo pipefail

SERVER_ADDR="rustdesk.itios.ru"
PUBLIC_KEY="QK8PKysfn9ps6Cjj7BvBgYc37OFWmLiOkNPqHFCUiEE="

echo "🦀 RustDesk Auto-Installer (rustdesk.itios.ru)"

# Скачиваем с GitHub напрямую (надёжнее)
LATEST="1.4.6"
TMP=$(mktemp -d)

detect_pkg() {
    command -v dpkg >/dev/null 2>&1 && echo deb && return
    command -v rpm >/dev/null 2>&1 && echo rpm && return
    echo appimage
}
PKG=$(detect_pkg)

case "$PKG" in
    deb)
        wget -q "https://github.com/rustdesk/rustdesk/releases/download/$LATEST/rustdesk-$LATEST-x86_64.deb" -O "$TMP/rustdesk.deb"
        sudo dpkg -i "$TMP/rustdesk.deb" || sudo apt-get install -f -y ;;
    rpm)
        wget -q "https://github.com/rustdesk/rustdesk/releases/download/$LATEST/rustdesk-$LATEST-x86_64.rpm" -O "$TMP/rustdesk.rpm"
        sudo rpm -Uvh "$TMP/rustdesk.rpm" ;;
    *)
        wget -q "https://github.com/rustdesk/rustdesk/releases/download/$LATEST/rustdesk-$LATEST-x86_64.AppImage" -O "$TMP/rustdesk.AppImage"
        chmod +x "$TMP/rustdesk.AppImage"
        echo "✅ AppImage: $TMP/rustdesk.AppImage"
        exit 0 ;;
esac

mkdir -p "$HOME/.config/rustdesk"
cat > "$HOME/.config/rustdesk/RustDesk2.toml" << TOML
[options]
custom-rendezvous-server = "rustdesk.itios.ru"
key = "QK8PKysfn9ps6Cjj7BvBgYc37OFWmLiOkNPqHFCUiEE="
relay-server = "rustdesk.itios.ru"
TOML

echo "✅ Configured: $SERVER_ADDR"
rm -rf "$TMP"
