#!/bin/bash
# Install official RustDesk 1.5.3 from this site, then apply self-host config
# with `rustdesk --config`. Does not patch the official package.
set -euo pipefail
BASE="https://rest.zxy100.top/neardesk/downloads"
CFG_URL="https://rest.zxy100.top/neardesk/rustdesk-config.txt"
DEBIG="rustdesk-1.5.3-x86_64.deb"
RPMIG="rustdesk-1.5.3-0.x86_64.rpm"
DEB_SUM="81096d2f65fd43352540c351bca15bb0712a2a6f9efa4c95e9fff25cb97b3b81"
RPM_SUM="bd5d036392ba6197ece89232c52e71c570e1160f9ac3c1a895c8383ac5911c70"

if [[ ${EUID} -ne 0 ]]; then
  echo "请使用 root 或 sudo 运行：$0"
  exec sudo bash "$0" "$@"
fi

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
cd "$tmpdir"
cfg=$(curl -fsSL "$CFG_URL" | tr -d '\n\r')
if [[ -z "$cfg" ]]; then
  echo "无法获取本站配置文本"
  exit 1
fi

. /etc/os-release 2>/dev/null || true
if [[ "${ID:-}" == "debian" || "${ID:-}" == "ubuntu" || "${ID_LIKE:-}" == *debian* ]]; then
  curl -fL "$BASE/official/$DEBIG" -o "$DEBIG"
  echo "$DEB_SUM  $DEBIG" | sha256sum -c
  apt-get install -y "./$DEBIG"
elif [[ "${ID:-}" == "fedora" || "${ID:-}" == "centos" || "${ID:-}" == "rhel" || "${ID:-}" == "rocky" || "${ID:-}" == "almalinux" || "${ID_LIKE:-}" == *rhel* ]]; then
  curl -fL "$BASE/official/$RPMIG" -o "$RPMIG"
  echo "$RPM_SUM  $RPMIG" | sha256sum -c
  if command -v dnf >/dev/null; then dnf install -y "./$RPMIG"; else yum localinstall -y "./$RPMIG"; fi
else
  echo "未自动识别的系统，请先手动安装本站镜像的 deb/rpm，再运行：rustdesk --config \"\$(curl -fsSL $CFG_URL)\""
  exit 1
fi

rustdesk --config "$cfg"
systemctl restart rustdesk 2>/dev/null || true
echo "已安装官方 RustDesk 1.5.3，并写入本站 ID/中继/API/Key。"
