#!/bin/bash
# OneDot Systems - Remote Support Agent (macOS)
# Usage:  curl -fsSL https://help.onedotsystems.com/downloads/macos/install-onedot-support.sh | sudo bash
# Optional: VERSION=1.3.9 to pin a RustDesk release (default: latest).

set -euo pipefail

# --- OneDot Systems server settings ---
ID_SERVER="rust.onedotsystems.com"
API_SERVER="https://rust.onedotsystems.com"
KEY="VrszR71y9BuwelF2PS6rTNeP6fRKkRq8FqoucT3YZdI="
# --------------------------------------

say() { printf '\033[36m[OneDot]\033[0m %s\n' "$*"; }

if [ "$(id -u)" -ne 0 ]; then
  echo "Please run with sudo:  curl -fsSL https://help.onedotsystems.com/downloads/macos/install-onedot-support.sh | sudo bash" >&2
  exit 1
fi

CONSOLE_USER="$(stat -f%Su /dev/console)"

VERSION="${VERSION:-}"
if [ -z "$VERSION" ]; then
  say "Finding the latest RustDesk release..."
  VERSION="$(curl -fsSL https://api.github.com/repos/rustdesk/rustdesk/releases/latest \
    | grep -m1 '"tag_name"' | sed -E 's/.*"tag_name": *"v?([^"]+)".*/\1/')"
fi
VERSION="${VERSION#v}"

case "$(uname -m)" in
  arm64)  ARCH="aarch64" ;;
  x86_64) ARCH="x86_64"  ;;
  *) echo "Unsupported CPU: $(uname -m)" >&2; exit 1 ;;
esac

URL="https://github.com/rustdesk/rustdesk/releases/download/${VERSION}/rustdesk-${VERSION}-${ARCH}.dmg"
DMG="/tmp/rustdesk-${VERSION}-${ARCH}.dmg"
MNT="/Volumes/OneDotRustDesk"

say "Downloading RustDesk ${VERSION} (${ARCH})..."
curl -fL --progress-bar "$URL" -o "$DMG"

say "Installing..."
hdiutil detach "$MNT" -quiet 2>/dev/null || true
hdiutil attach "$DMG" -nobrowse -quiet -mountpoint "$MNT"
rm -rf /Applications/RustDesk.app
cp -R "$MNT/RustDesk.app" /Applications/
hdiutil detach "$MNT" -quiet || true
xattr -dr com.apple.quarantine /Applications/RustDesk.app 2>/dev/null || true
rm -f "$DMG"

APP="/Applications/RustDesk.app/Contents/MacOS/RustDesk"

say "Applying OneDot Systems server settings for ${CONSOLE_USER}..."
sudo -u "$CONSOLE_USER" "$APP" --option custom-rendezvous-server "$ID_SERVER" || true
sudo -u "$CONSOLE_USER" "$APP" --option api-server "$API_SERVER" || true
sudo -u "$CONSOLE_USER" "$APP" --option key "$KEY" || true

say "Starting RustDesk..."
sudo -u "$CONSOLE_USER" open -a RustDesk

cat <<'EOF'

Almost done. macOS needs your permission before support can see and control the screen:
  System Settings > Privacy & Security
    - Accessibility          -> turn ON for RustDesk
    - Screen & System Audio Recording -> turn ON for RustDesk
    - Input Monitoring       -> turn ON for RustDesk
Then give your technician the ID shown in the RustDesk window.
EOF
