#!/usr/bin/env bash
# Mac: RDP к Fedora (xrdp, порт 3389).
#   bash docs/old_mac/scripts/connect-rdp-fedora.sh
set -euo pipefail

ENV="${OLD_MAC_FEDORA_ENV:-$HOME/.config/old_mac/fedora.env}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

if [ -f "$ENV" ]; then
  # shellcheck disable=SC1090
  source "$ENV"
fi

FEDORA_USER="${FEDORA_USER:-p}"
FEDORA_RDP_PORT="${FEDORA_RDP_PORT:-3389}"

# Порядок хостов: BT PAN → mDNS → hotspot IP
HOSTS=(
  "${FEDORA_BT_IP:-172.20.99.1}"
  "${FEDORA_HOST:-fedora.local}"
  "${FEDORA_IP:-10.23.120.30}"
)

reachable() {
  nc -z -G 2 -w 2 "$1" "$FEDORA_RDP_PORT" 2>/dev/null
}

TARGET=""
for h in "${HOSTS[@]}"; do
  if reachable "$h"; then
    TARGET="$h"
    break
  fi
done

if [ -z "$TARGET" ]; then
  printf 'RDP %s недоступен на:\n' "$FEDORA_RDP_PORT"
  for h in "${HOSTS[@]}"; do printf '  %s:%s\n' "$h" "$FEDORA_RDP_PORT"; done
  printf '\nПричина: изоляция хотспота или нет BT PAN.\n'
  printf '  bash %s/discover-fedora.sh\n' "$SCRIPT_DIR"
  printf '  docs/old_mac/REMOTE_ACCESS.md\n'
  exit 1
fi

printf 'RDP → %s:%s (user %s)\n' "$TARGET" "$FEDORA_RDP_PORT" "$FEDORA_USER"

if command -v xfreerdp >/dev/null 2>&1; then
  exec xfreerdp "/v:${TARGET}:${FEDORA_RDP_PORT}" "/u:${FEDORA_USER}" +clipboard /dynamic-resolution
fi

if [ -d "/Applications/Microsoft Remote Desktop.app" ]; then
  exec open -a "Microsoft Remote Desktop"
fi

printf 'Установите клиент:\n'
printf '  brew install freerdp\n'
printf '  или Microsoft Remote Desktop из App Store\n'
printf '\nВручную: %s:%s user %s\n' "$TARGET" "$FEDORA_RDP_PORT" "$FEDORA_USER"
exit 1
