#!/bin/bash
set -euo pipefail
cfg='9JSPZJzY3YXdvtGd1JzQyN0b3V0MudEMycWeEtWdwMDTvh2N2cTakd2aUBFTSJiOikXZrJCLiIiOikGchJCLiIiOikXYsVmciwiI6lHeuEWakVWbzlGbslmYus2clRGdzVnciojI0N3boJye'
echo 'Billis Media RustDesk setup'
echo 'This installs RustDesk if missing and configures rustdesk.billismedia.xyz.'
echo 'Close any current RustDesk sessions before continuing.'
read -r -p 'Press Enter to continue, or Control-C to cancel. ' answer
if [ "$(uname -s)" != Darwin ]; then echo 'This setup is for macOS.'; exit 1; fi
if [ "$(id -u)" -eq 0 ]; then echo 'Run as your normal user; setup requests administrator access when needed.'; exit 1; fi
tmp=$(mktemp -d)
mounted=0
server_pid=''
cleanup() {
  if [ -n "$server_pid" ]; then sudo kill "$server_pid" 2>/dev/null || true; fi
  if [ "$mounted" = 1 ]; then hdiutil detach "$tmp/mount" >/dev/null || true; fi
  rm -rf "$tmp"
}
trap cleanup EXIT
if [ ! -d /Applications/RustDesk.app ]; then
  case "$(uname -m)" in
    arm64) url='https://github.com/rustdesk/rustdesk/releases/download/1.5.0/rustdesk-1.5.0-aarch64.dmg'
    expected='3929b0a4321e7d0f561a317059798be882d65decc59681eb77061f8efe56fbf4' ;;
    x86_64) url='https://github.com/rustdesk/rustdesk/releases/download/1.5.0/rustdesk-1.5.0-x86_64.dmg'
    expected='1ca3cbfbe7f2bd28b50c93fcd50d4a0b671dc76d18be27cea99d3a65767eb526' ;;
    *) echo 'Unsupported Mac architecture.'; exit 1 ;;
  esac
  curl --fail --location --proto '=https' --tlsv1.2 "$url" -o "$tmp/rustdesk.dmg"
  actual=$(shasum -a 256 "$tmp/rustdesk.dmg" | awk '{print $1}')
  [ "$actual" = "$expected" ] || { echo 'Download verification failed.'; exit 1; }
  mkdir "$tmp/mount"
  hdiutil attach -nobrowse -readonly -mountpoint "$tmp/mount" "$tmp/rustdesk.dmg"
  mounted=1
  sudo ditto "$tmp/mount/RustDesk.app" /Applications/RustDesk.app
  hdiutil detach "$tmp/mount"
  mounted=0
fi
app=/Applications/RustDesk.app/Contents/MacOS/RustDesk
sudo -v
if ! pgrep -f '/Applications/RustDesk.app/Contents/MacOS/RustDesk.*--server' >/dev/null; then
  sudo "$app" --server &
  server_pid=$!
  sleep 3
fi
sudo "$app" --config "$cfg"
if [ -n "$server_pid" ]; then sudo kill "$server_pid" 2>/dev/null || true; server_pid=''; fi
open /Applications/RustDesk.app
echo 'Configuration command completed. Check Settings > Network for rustdesk.billismedia.xyz.'
echo 'Approve Screen Recording and Accessibility when macOS requests them.'
echo 'If settings were not applied, use Import Server Config on the support page.'
read -r -p 'Press Enter to close. ' answer
