#!/bin/bash
set -euo pipefail
BASE_URL="https://help.vserv.online"
CONFIG_STRING="9JSPn52K4JEUwoEVOh2aGN2b4lmazEVNV5GOzMET4pVW3A1TmhWT3RlaDVTcyIiOikXZrJCLiUmbpxmbv5idyV2c25CcsVGaiojI0N3boJye"
CHECKIN_TOKEN="8831c76cbd31dd57b6109a437cba73f7b09595753f16ef9c8e860417f868ef75"
CHECKIN_URL="$BASE_URL/api/checkin"
APP_PATH="/Applications/RustDesk.app"
APP_BIN="$APP_PATH/Contents/MacOS/RustDesk"
TMP_DIR="$(mktemp -d /tmp/rustdesk-help-install.XXXXXX)"
MOUNT_POINT="$TMP_DIR/mount"
mkdir -p "$MOUNT_POINT"
cleanup() {
  # Detach before removing the temp directory; otherwise macOS prints one
  # read-only filesystem error for every file still mounted from the DMG.
  if mount | grep -Fq " $MOUNT_POINT "; then
    hdiutil detach "$MOUNT_POINT" -force >/dev/null 2>&1 || true
  fi
  rm -rf "$TMP_DIR" 2>/dev/null || true
}
trap cleanup EXIT

if [ "$(uname -s)" != "Darwin" ]; then
  echo "This installer must be run on a Mac." >&2
  exit 1
fi
command -v curl >/dev/null || { echo "curl is required but was not found." >&2; exit 1; }
command -v hdiutil >/dev/null || { echo "hdiutil is required but was not found." >&2; exit 1; }

ARCH="$(uname -m)"
case "$ARCH" in
  arm64|aarch64)
    DMG="RustDesk-help.vserv.online-macos-aarch64.dmg"
    ;;
  x86_64|i386)
    DMG="RustDesk-help.vserv.online-macos-x86_64.dmg"
    ;;
  *)
    echo "Unsupported Mac CPU architecture: $ARCH" >&2
    exit 1
    ;;
esac

echo "Detected Mac architecture: $ARCH"
echo "Downloading $DMG ..."
curl --fail --location --progress-bar -o "$TMP_DIR/$DMG" "$BASE_URL/$DMG"

echo "Mounting DMG..."
hdiutil attach "$TMP_DIR/$DMG" -nobrowse -quiet -mountpoint "$MOUNT_POINT"

SRC_APP="$(find "$MOUNT_POINT" -maxdepth 3 -name "RustDesk.app" -type d | head -n 1)"
if [ -z "$SRC_APP" ]; then
  echo "Could not find RustDesk.app inside the DMG." >&2
  exit 1
fi

echo "Force-closing RustDesk if it is running..."
osascript -e 'tell application "RustDesk" to quit' >/dev/null 2>&1 || true
# Give the normal quit a moment, then terminate any remaining client/helper processes.
sleep 2
pkill -TERM -x RustDesk >/dev/null 2>&1 || true
pkill -TERM -f '/Applications/RustDesk.app/Contents/MacOS/' >/dev/null 2>&1 || true
sleep 1
pkill -KILL -x RustDesk >/dev/null 2>&1 || true
pkill -KILL -f '/Applications/RustDesk.app/Contents/MacOS/' >/dev/null 2>&1 || true
sleep 1

echo "Overwriting RustDesk in Applications..."
if [ -w "/Applications" ]; then
  rm -rf "$APP_PATH"
  ditto "$SRC_APP" "$APP_PATH"
else
  sudo rm -rf "$APP_PATH"
  sudo ditto "$SRC_APP" "$APP_PATH"
fi
# The upstream bundle is sometimes marked as LSUIElement, which makes Finder
# launch only a hidden menu-bar agent. Remove it so the normal RustDesk window opens.
/usr/libexec/PlistBuddy -c "Delete :LSUIElement" "$APP_PATH/Contents/Info.plist" >/dev/null 2>&1 || true
# Editing Info.plist invalidates the original signature; re-sign locally so macOS can launch it.
if command -v codesign >/dev/null 2>&1; then
  codesign --force --deep --sign - --timestamp=none "$APP_PATH" >/dev/null 2>&1 || true
fi

echo "Removing quarantine flag if present..."
xattr -dr com.apple.quarantine "$APP_PATH" >/dev/null 2>&1 || sudo xattr -dr com.apple.quarantine "$APP_PATH" >/dev/null 2>&1 || true

echo "Applying Help.VserV.online RustDesk server configuration..."
if [ -x "$APP_BIN" ]; then
  "$APP_BIN" --config "$CONFIG_STRING" >/dev/null 2>&1 || true
else
  echo "Warning: RustDesk executable was not found at $APP_BIN" >&2
fi

echo "Opening RustDesk..."
open "$APP_PATH" || true

json_escape() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}
check_in() {
  RID=""
  if [ -x "$APP_BIN" ]; then
    for i in $(seq 1 24); do
      OUT="$($APP_BIN --get-id 2>/dev/null || true)"
      RID="$(printf '%s' "$OUT" | tr -cd '0-9')"
      [ -n "$RID" ] && break
      sleep 5
    done
  fi
  HOSTNAME="$(scutil --get ComputerName 2>/dev/null || hostname)"
  USERNAME="$(id -un 2>/dev/null || whoami)"
  OS="$(sw_vers -productName 2>/dev/null) $(sw_vers -productVersion 2>/dev/null)"
  LOCAL_IP="$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || true)"
  [ -n "$RID" ] || RID="mac-$(printf '%s' "$HOSTNAME" | tr -cd 'A-Za-z0-9_.-')"
  PAYLOAD=$(printf '{"id":"%s","hostname":"%s","username":"%s","os":"%s","arch":"%s","app_version":"macos-installer-checkin-1","local_ip":"%s"}' \
    "$(json_escape "$RID")" "$(json_escape "$HOSTNAME")" "$(json_escape "$USERNAME")" \
    "$(json_escape "$OS")" "$(json_escape "$ARCH")" "$(json_escape "$LOCAL_IP")")
  # Registration is best-effort and must never make a successful install look failed.
  curl --fail --silent --max-time 10 -X POST "$CHECKIN_URL" \
    -H "X-Checkin-Token: $CHECKIN_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD" >/dev/null 2>&1 || true
}

echo "Registering this Mac in the Help.VserV.online admin portal..."
check_in &

echo ""
echo "Done. RustDesk is installed and configured for help.vserv.online."
echo "If macOS asks for permissions, allow RustDesk in:"
echo "  Apple menu > System Settings > Privacy & Security > Accessibility"
echo "  Apple menu > System Settings > Privacy & Security > Screen Recording"
echo "  Apple menu > System Settings > Privacy & Security > Input Monitoring, if shown"
