#!/usr/bin/env bash
# Mac: подключиться к Fedora по SSH (LAN или BT PAN).
#   bash docs/old_mac/scripts/connect-fedora.sh [ssh args...]
set -euo pipefail

ENV="${OLD_MAC_FEDORA_ENV:-$HOME/.config/old_mac/fedora.env}"
KEY="$HOME/.ssh/id_ed25519_fedora"
EXTRA_ARGS=("$@")

if [ -f "$ENV" ]; then
  # shellcheck disable=SC1090
  source "$ENV"
fi
FEDORA_USER="${FEDORA_USER:-p}"

try_host() {
  local host="$1"
  local label="$2"
  if ssh -i "$KEY" -o ConnectTimeout=3 -o BatchMode=yes \
    -o StrictHostKeyChecking=accept-new \
    "$host" "echo ok" >/dev/null 2>&1; then
    printf '[ok] SSH через %s (%s)\n' "$label" "$host"
    exec ssh -i "$KEY" -o StrictHostKeyChecking=accept-new "$host" "${EXTRA_ARGS[@]}"
  fi
  return 1
}

[ -f "$KEY" ] || {
  printf 'Нет ключа %s — сначала: bash docs/old_mac/scripts/setup-remote-mac.sh\n' "$KEY"
  exit 1
}

printf 'Пробую подключение к Fedora (user %s)…\n' "$FEDORA_USER"

try_host "fedora-mbp" "ssh config / mDNS" || \
try_host "fedora-mbp-bt" "BT PAN" || \
try_host "${FEDORA_USER}@${FEDORA_HOST:-fedora.local}" "mDNS" || \
try_host "${FEDORA_USER}@${FEDORA_IP:-10.23.120.30}" "hotspot IP" || \
try_host "${FEDORA_USER}@${FEDORA_BT_IP:-172.20.99.1}" "BT Fedora IP" || {
  printf '\nSSH недоступен (ключ не принят или нет сети).\n'
  printf '  Парольный bootstrap: bash docs/old_mac/scripts/bootstrap-ssh-fedora.sh\n'
  printf '  Диагностика: bash docs/old_mac/scripts/discover-fedora.sh\n'
  exit 1
}
