#!/bin/bash
set -euo pipefail
HOST='remote.autonomyict.com.au'
KEY='oT+pZtSc+DHijhzl9+61U9K7HW772rDEA4SMaP9kMhs='
CFG='host=remote.autonomyict.com.au,key=oT+pZtSc+DHijhzl9+61U9K7HW772rDEA4SMaP9kMhs='
VERSION='1.4.9'
BASE='https://github.com/rustdesk/rustdesk/releases/download/1.4.9'

if [ "${EUID}" -ne 0 ]; then
  echo "Re-running with sudo..."
  exec sudo bash "$0" "$@"
fi
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
cd "$TMP"
. /etc/os-release
ID_LIKE_LOWER="${ID_LIKE:-}"
ID_LIKE_LOWER="${ID_LIKE_LOWER,,}"
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64) RARCH=x86_64 ;;
  aarch64|arm64) RARCH=aarch64 ;;
  *) echo "Unsupported arch: $ARCH"; exit 1 ;;
esac
if [[ "${ID}" == "debian" || "${ID}" == "ubuntu" || "$ID_LIKE_LOWER" == *debian* || "$ID_LIKE_LOWER" == *ubuntu* ]]; then
  PKG="rustdesk-${VERSION}-${RARCH}.deb"
  curl -fL --retry 3 -o "$PKG" "$BASE/$PKG"
  apt-get update
  apt-get install -y "./$PKG"
elif [[ "${ID}" == "fedora" || "${ID}" == "rhel" || "${ID}" == "centos" || "$ID_LIKE_LOWER" == *rhel* || "$ID_LIKE_LOWER" == *fedora* ]]; then
  PKG="rustdesk-${VERSION}-0.${RARCH}.rpm"
  curl -fL --retry 3 -o "$PKG" "$BASE/$PKG"
  if command -v dnf >/dev/null; then dnf install -y "./$PKG"; else yum localinstall -y "./$PKG"; fi
else
  echo "Unsupported Linux distro: ${PRETTY_NAME:-unknown}. Download the AppImage and configure manually."
  exit 1
fi
rustdesk --config "$CFG" || true
systemctl enable --now rustdesk >/dev/null 2>&1 || systemctl restart rustdesk >/dev/null 2>&1 || true
echo "RustDesk installed/configured. Server: $HOST"
