#!/bin/bash
# THN Remote Support - macOS Installer
set -e

SERVER="help.kriskirkland.com"
KEY="I15NQEE2HU2fPQQLpVfluq8ShuNq0L4F6MGUo5Vg7Dg="
ARCH=$(uname -m)

echo "Fetching latest RustDesk version..."
LVER=$(curl -s https://api.github.com/repos/rustdesk/rustdesk/releases/latest | grep '"tag_name"' | cut -d'"' -f4)

if [ "$ARCH" = "arm64" ]; then
    DMG_URL=$(curl -s "https://api.github.com/repos/rustdesk/rustdesk/releases/latest" \
        | grep '"browser_download_url"' | grep '\.dmg' | grep 'aarch64' | cut -d'"' -f4 | head -1)
else
    DMG_URL=$(curl -s "https://api.github.com/repos/rustdesk/rustdesk/releases/latest" \
        | grep '"browser_download_url"' | grep '\.dmg' | grep 'x86_64' | cut -d'"' -f4 | head -1)
fi

[ -z "$DMG_URL" ] && DMG_URL=$(curl -s "https://api.github.com/repos/rustdesk/rustdesk/releases/latest" \
    | grep '"browser_download_url"' | grep '\.dmg' | cut -d'"' -f4 | head -1)

echo "Downloading RustDesk $LVER for $ARCH..."
curl -L "$DMG_URL" -o /tmp/rustdesk.dmg

echo "Installing..."
hdiutil attach /tmp/rustdesk.dmg -quiet -nobrowse
MOUNT=$(hdiutil info | grep RustDesk | awk '{print $1}' | head -1)
APP=$(find /Volumes -name "RustDesk.app" 2>/dev/null | head -1)
cp -R "$APP" /Applications/
hdiutil detach "$(dirname "$APP")" -quiet 2>/dev/null || true
rm /tmp/rustdesk.dmg

CONFIG_DIR="$HOME/Library/Application Support/com.carriez.RustDesk"
mkdir -p "$CONFIG_DIR"
cat > "$CONFIG_DIR/RustDesk2.toml" << TOML
rendezvous_server = 'help.kriskirkland.com'
nat_type = 1
serial = 3

[options]
key = 'I15NQEE2HU2fPQQLpVfluq8ShuNq0L4F6MGUo5Vg7Dg='
custom-rendezvous-server = 'help.kriskirkland.com'
api-server = 'https://help.kriskirkland.com'
relay-server = 'help.kriskirkland.com'
enable-audio = 'N'
TOML

echo ""
echo "Done! RustDesk installed at /Applications/RustDesk.app"
echo "Pre-configured for $SERVER — just launch and share your ID."
