#!/bin/bash
# =============================================================
#  JPIT Remote Support - Client (macOS 11+, Intel / Apple Silicon)
#  For customers to download and run when they request support.
#  - Installs RustDesk pointed at the JPIT self-hosted server
#  - Every connection must be ACCEPTED by the customer on screen (attended)
#  - Uses built-in one-time password; NO fixed/unattended password is set
#
#  NOTE: this plain .command is the UNSIGNED fallback (customer must
#  right-click > Open the first time). For a clean, no-warning customer
#  experience, build the signed+notarized .pkg with build_signed_pkg.command.
# =============================================================

# ======== Config (server only - no password) ========
SERVER_HOST="support.johnpan.com.au"
SERVER_KEY="hnlVp0HwJU25CiuTdrTD02uPUNAqZpJbm56dmjCwRfk="
CONFIG_STRING="==Qfi0zamJ1dDpWbkZTNtJmSwpVcB5UVQVnMwQEVyRGV1l2Q1ITVKdHSwAnVs5GaiojI5V2aiwiIiojIpBXYiwiIiojI5FGblJnIsISdh5SbvNmLuFGcuh2bq5Cdy9GcwV3ciojI0N3boJye"
# =====================================================

set -u
APP="/Applications/RustDesk.app"
BIN="$APP/Contents/MacOS/RustDesk"
DAEMON_PLIST="/Library/LaunchDaemons/com.carriez.RustDesk_service.plist"
AGENT_PLIST="/Library/LaunchAgents/com.carriez.RustDesk_server.plist"
LOG="/tmp/JPIT-RustDesk-Client.log"

say()  { printf '\033[1;36m[JPIT]\033[0m %s\n' "$*"; }
fail() { printf '\033[1;31m[JPIT] Install failed: %s\033[0m\n' "$*"; echo "Log: $LOG"; read -r -p "Press Enter to close..." _ </dev/tty 2>/dev/null || true; exit 1; }

if [ "$(id -u)" -ne 0 ]; then
  echo "======================================"
  echo "   JPIT Remote Support - RustDesk"
  echo "======================================"
  echo "Enter this Mac's login password (it won't be shown), then press Enter:"
  exec sudo /bin/bash "$0" "$@"
fi
exec > >(tee -a "$LOG") 2>&1

CU=$(stat -f%Su /dev/console)
{ [ -z "$CU" ] || [ "$CU" = "root" ]; } && fail "Please run while logged in as a normal desktop user."
CU_UID=$(id -u "$CU")
as_user() { launchctl asuser "$CU_UID" sudo -u "$CU" "$@"; }

if [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = "1" ]; then ARCH="aarch64"; else ARCH="x86_64"; fi
say "Architecture: $ARCH, user: $CU"

HERE="$(cd "$(dirname "$0")" 2>/dev/null && pwd)"
DMG=$(ls "$HERE"/rustdesk-*-"$ARCH".dmg 2>/dev/null | head -1)
if [ -z "$DMG" ]; then
  say "Checking for the latest RustDesk version..."
  URL=$(curl -fsSL -H "User-Agent: JPIT-Installer" https://api.github.com/repos/rustdesk/rustdesk/releases/latest \
        | grep -o '"browser_download_url": *"[^"]*"' | cut -d'"' -f4 \
        | grep -E "/rustdesk-[0-9.]+-$ARCH\.dmg$" | head -1)
  [ -n "$URL" ] || fail "Could not find a $ARCH build (GitHub unreachable?)"
  DMG="/tmp/$(basename "$URL")"
  say "Downloading $(basename "$URL") ..."
  curl -fL --progress-bar -o "$DMG" "$URL" || fail "Download failed"
fi

launchctl bootout system/com.carriez.RustDesk_service 2>/dev/null || true
launchctl bootout "gui/$CU_UID/com.carriez.RustDesk_server" 2>/dev/null || true
pkill -x RustDesk 2>/dev/null || true
pkill -f "/Applications/RustDesk.app/Contents/MacOS/service" 2>/dev/null || true
sleep 1

say "Installing RustDesk into /Applications ..."
MNT=$(mktemp -d /tmp/rustdesk_mnt.XXXX)
hdiutil attach -nobrowse -readonly -quiet -mountpoint "$MNT" "$DMG" || fail "Could not mount DMG"
rm -rf "$APP"
ditto "$MNT/RustDesk.app" "$APP" || { hdiutil detach -quiet "$MNT"; fail "Copying app failed"; }
hdiutil detach -quiet "$MNT"; rmdir "$MNT" 2>/dev/null
xattr -dr com.apple.quarantine "$APP" 2>/dev/null || true

say "Installing background service (starts at boot)..."
cat > "$DAEMON_PLIST" <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.carriez.RustDesk_service</string>
  <key>AssociatedBundleIdentifiers</key><string>com.carriez.rustdesk</string>
  <key>KeepAlive</key><true/>
  <key>ThrottleInterval</key><integer>1</integer>
  <key>ProgramArguments</key><array>
    <string>/bin/sh</string><string>-c</string><string>/Applications/RustDesk.app/Contents/MacOS/service</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>WorkingDirectory</key><string>/Applications/RustDesk.app/Contents/MacOS/</string>
  <key>StandardErrorPath</key><string>/var/log/rustdesk_service.err</string>
  <key>StandardOutPath</key><string>/var/log/rustdesk_service.out</string>
</dict></plist>
PLIST
cat > "$AGENT_PLIST" <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.carriez.RustDesk_server</string>
  <key>AssociatedBundleIdentifiers</key><string>com.carriez.rustdesk</string>
  <key>LimitLoadToSessionType</key><array><string>LoginWindow</string><string>Aqua</string></array>
  <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/><key>AfterInitialDemand</key><false/></dict>
  <key>ThrottleInterval</key><integer>1</integer>
  <key>RunAtLoad</key><true/>
  <key>ProgramArguments</key><array>
    <string>/Applications/RustDesk.app/Contents/MacOS/RustDesk</string><string>--server</string>
  </array>
  <key>WorkingDirectory</key><string>/Applications/RustDesk.app/Contents/MacOS/</string>
  <key>ProcessType</key><string>Interactive</string>
</dict></plist>
PLIST
chown root:wheel "$DAEMON_PLIST" "$AGENT_PLIST"; chmod 644 "$DAEMON_PLIST" "$AGENT_PLIST"
mkdir -p /var/root/Library/Preferences/com.carriez.RustDesk
launchctl bootstrap system "$DAEMON_PLIST" 2>/dev/null || launchctl load -w "$DAEMON_PLIST"
launchctl bootstrap "gui/$CU_UID" "$AGENT_PLIST" 2>/dev/null || true
sleep 5

say "Writing server configuration..."
"$BIN" --config "$CONFIG_STRING"
"$BIN" --option custom-rendezvous-server "$SERVER_HOST"
"$BIN" --option key "$SERVER_KEY"
# Attended: one-time temporary password + Accept click. No fixed password.
say "Setting attended mode (connection requires customer approval)..."
"$BIN" --option verification-method use-temporary-password
"$BIN" --option approve-mode click

launchctl kickstart -k system/com.carriez.RustDesk_service 2>/dev/null || true
launchctl kickstart -k "gui/$CU_UID/com.carriez.RustDesk_server" 2>/dev/null || true
sleep 6

ID=""
for _ in 1 2 3 4 5 6 7 8 9 10; do
  ID=$("$BIN" --get-id 2>/dev/null | tr -d '[:space:]'); [ -n "$ID" ] && break; sleep 2
done
[ -n "$ID" ] && echo -n "$ID" | as_user pbcopy 2>/dev/null || true
say "Done. ID: $ID"

as_user osascript <<OSA 2>/dev/null
display dialog "Installation complete!

Your remote support ID: $ID
(also copied to the clipboard)

Read this ID to the JPIT technician - no password is needed.
When we connect, a request appears on your screen - click Accept to let us in. Close RustDesk any time to end the session.

Last step: in the System Settings > Privacy & Security window that opens next, turn ON for RustDesk:
  1. Screen Recording
  2. Accessibility
otherwise we will only see a black screen / cannot control the mouse." buttons {"OK, open settings"} default button 1 with title "JPIT Remote Support" with icon note
OSA
as_user open -a "$APP" 2>/dev/null || true
as_user open "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" 2>/dev/null
sleep 2
as_user open "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" 2>/dev/null
exit 0
