#!/bin/bash
set -euo pipefail

server="rustdesk.stsaz.com"
public_key="OAzaj7wyLoUJCegm+iEXGL+yl7o9AkqY7DeitGXc7JQ="
package_dir="$(cd "$(dirname "$0")" && pwd)"
arch="$(uname -m)"

case "${arch}" in
  arm64) dmg_name="rustdesk-1.4.9-aarch64.dmg"; expected_sha="f7935597b247d42c8f2a2ed71176a9f5868018cd9e1a33b8096418a668c8caf0" ;;
  x86_64) dmg_name="rustdesk-1.4.9-x86_64.dmg"; expected_sha="fa1129a0635019f9c5841937942cc2b08be028a192f47c009edde7e53812904e" ;;
  *) echo "Unsupported Mac architecture: ${arch}"; read -r -p "Press Return to close."; exit 1 ;;
esac

dmg="${package_dir}/${dmg_name}"
[[ -f "${dmg}" ]] || { echo "The required RustDesk installer is missing."; read -r -p "Press Return to close."; exit 1; }
actual_sha="$(shasum -a 256 "${dmg}" | awk '{print $1}')"
[[ "${actual_sha}" == "${expected_sha}" ]] || { echo "Security check failed: the RustDesk installer checksum does not match."; read -r -p "Press Return to close."; exit 1; }

echo "STS Remote Support will install the official RustDesk client and configure ${server}."
echo "macOS will ask for an administrator password."
sudo -v

mount_point="$(mktemp -d /tmp/sts-rustdesk.XXXXXX)"
cleanup() {
  hdiutil detach "${mount_point}" -quiet >/dev/null 2>&1 || true
  rmdir "${mount_point}" >/dev/null 2>&1 || true
}
trap cleanup EXIT
hdiutil attach "${dmg}" -mountpoint "${mount_point}" -nobrowse -quiet
[[ -d "${mount_point}/RustDesk.app" ]] || { echo "RustDesk.app was not found in the official installer."; exit 1; }

osascript -e 'tell application "RustDesk" to quit' >/dev/null 2>&1 || true
sleep 2
if [[ -d /Applications/RustDesk.app ]]; then
  backup="/Applications/RustDesk.app.sts-backup-$(date +%Y%m%d-%H%M%S)"
  echo "Preserving the existing RustDesk application at ${backup}"
  sudo mv /Applications/RustDesk.app "${backup}"
fi
sudo ditto "${mount_point}/RustDesk.app" /Applications/RustDesk.app

config="host=${server},key=${public_key},relay=${server},"
rustdesk_bin="/Applications/RustDesk.app/Contents/MacOS/RustDesk"
sudo "${rustdesk_bin}" --config "${config}"
# RustDesk normally learns the relay from HBBS, but set every value explicitly so
# the Network screen also contains the STS relay on current macOS clients.
sudo "${rustdesk_bin}" --option custom-rendezvous-server "${server}"
sudo "${rustdesk_bin}" --option relay-server "${server}"
sudo "${rustdesk_bin}" --option key "${public_key}"

console_user="$(stat -f '%Su' /dev/console)"
if [[ -n "${console_user}" && "${console_user}" != root ]]; then
  # macOS keeps the interactive user's RustDesk profile separate from the
  # elevated service profile. Write the same network settings for the visible UI.
  console_group="$(id -gn "${console_user}")"
  console_home="$(dscl . -read "/Users/${console_user}" NFSHomeDirectory | awk '{print $2}')"
  user_config_dir="${console_home}/Library/Preferences/com.carriez.RustDesk"
  user_config="${user_config_dir}/RustDesk2.toml"
  sudo install -d -m 700 -o "${console_user}" -g "${console_group}" "${user_config_dir}"
  if [[ -f "${user_config}" ]]; then
    sudo cp -p "${user_config}" "${user_config}.sts-backup-$(date +%Y%m%d-%H%M%S)"
  fi
  config_candidate="$(mktemp /tmp/sts-rustdesk-user-config.XXXXXX)"
  printf "rendezvous_server = '%s:21116'\n\n[options]\ncustom-rendezvous-server = '%s'\nrelay-server = '%s'\nkey = '%s'\n" \
    "${server}" "${server}" "${server}" "${public_key}" > "${config_candidate}"
  sudo install -m 600 -o "${console_user}" -g "${console_group}" "${config_candidate}" "${user_config}"
  unlink "${config_candidate}"
  sudo -u "${console_user}" open -n /Applications/RustDesk.app
else
  open -n /Applications/RustDesk.app
fi

echo
echo "RustDesk is installed and configured for STS Remote Support."
echo "In macOS System Settings, approve Screen Recording and Accessibility when prompted."
echo "Tell your technician the ID and one-time password shown in RustDesk."
read -r -p "Press Return to close this window."
