#!/bin/bash
# Download the official RustDesk 1.5.3 DMG from this site, copy to /Applications,
# then apply self-host config with the official --config switch.
# The DMG itself is unmodified so Apple notarization stays intact.
set -euo pipefail
BASE="https://rest.zxy100.top/neardesk/downloads/official"
CFG_URL="https://rest.zxy100.top/neardesk/rustdesk-config.txt"
X64="rustdesk-1.5.3-x86_64.dmg"
ARM="rustdesk-1.5.3-aarch64.dmg"
X64_SUM="74d06e6b2e273a128e8d36313e30d47db2063f453a4235ed4d9e5cdfdf9be538"
ARM_SUM="e6d30fa1633d772c48935907c208ca4e555a856fb2038af3aaa87a327c29360b"

if [[ $(id -u) -ne 0 ]]; then
  echo "需要管理员权限以写入 /Applications，将请求 sudo。"
  exec sudo bash "$0" "$@"
fi

arch=$(uname -m)
if [[ $arch == "arm64" ]]; then
  file=$ARM; sum=$ARM_SUM
else
  file=$X64; sum=$X64_SUM
fi

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"; hdiutil detach "$tmpdir/mnt" >/dev/null 2>&1 || true' EXIT
cd "$tmpdir"
curl -fL "$BASE/$file" -o "$file"
echo "$sum  $file" | shasum -a 256 -c
mkdir -p mnt
hdiutil attach "$file" -mountpoint "$tmpdir/mnt" -nobrowse
cp -R "$tmpdir/mnt/RustDesk.app" /Applications/
hdiutil detach "$tmpdir/mnt" >/dev/null
cfg=$(curl -fsSL "$CFG_URL" | tr -d '\n\r')
/Applications/RustDesk.app/Contents/MacOS/RustDesk --config "$cfg"
echo "已安装官方 RustDesk 1.5.3，并写入本站 ID/中继/API/Key。即将打开客户端。"
open -n /Applications/RustDesk.app
