#!/bin/bash
# Leadway Technology - Remote Support (macOS)
# Downloads RustDesk, points it at the Leadway self-hosted server, and launches it
# so the client can read their ID + one-time password to the technician.

echo ""
echo "  Leadway Technology - Remote Support"
echo "  Preparing your secure support session..."
echo ""

SERVER="129.80.92.95"
KEY="4fwOpJtoqiaScR+jnAYmaUh16Qihnvib9OlQHeXrJ2Y="
BASE="https://rmm.leadwayit.com/quicksupport"

# Pick the right build for this Mac
if [ "$(uname -m)" = "arm64" ]; then
  DMG="rustdesk-aarch64.dmg"
else
  DMG="rustdesk-x86_64.dmg"
fi

TMP="/tmp/LeadwayRemoteSupport.dmg"
MNT="/Volumes/RustDesk-LW"

echo "  Downloading support tool, please wait..."
curl -L -s -o "$TMP" "$BASE/$DMG"
if [ ! -f "$TMP" ]; then
  echo "  Could not download the support tool. Check your connection or call 901-410-4121."
  read -p "  Press Enter to close..." _; exit 1
fi

# Install to /Applications (idempotent)
hdiutil attach "$TMP" -mountpoint "$MNT" -nobrowse >/dev/null 2>&1
cp -R "$MNT/RustDesk.app" "/Applications/" >/dev/null 2>&1
hdiutil detach "$MNT" >/dev/null 2>&1

# Run once so RustDesk creates its config directory, then close it
open -n /Applications/RustDesk.app >/dev/null 2>&1
sleep 6
pkill -x RustDesk >/dev/null 2>&1
sleep 2

# Point RustDesk at the Leadway server
CFG="$HOME/Library/Preferences/com.carriez.RustDesk"
mkdir -p "$CFG"
cat > "$CFG/RustDesk2.toml" <<EOF
[options]
custom-rendezvous-server = '$SERVER'
relay-server = '$SERVER'
api-server = ''
key = '$KEY'
EOF

# Launch for the session
open -n /Applications/RustDesk.app >/dev/null 2>&1

echo ""
echo "  RustDesk is starting."
echo "  Read the ID (9 digits) and the one-time password shown to your technician."
echo ""
echo "  If macOS asks, allow Screen Recording and Accessibility for RustDesk under"
echo "  System Settings > Privacy & Security so we can see and control the screen."
echo ""
read -p "  You can close this window. Press Enter..." _
