#!/usr/bin/env bash
# Mac: один раз скопировать SSH-ключ на Fedora (пароль из ~/.config/old_mac/fedora.env).
#   bash docs/old_mac/scripts/bootstrap-ssh-fedora.sh
set -euo pipefail

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

die() { printf 'error: %s\n' "$*" >&2; exit 1; }

[ -f "$ENV" ] || die "нет $ENV — создайте с FEDORA_USER и FEDORA_PASSWORD"
# shellcheck disable=SC1090
source "$ENV"

[ -f "$KEY" ] || die "нет ключа — bash docs/old_mac/scripts/setup-remote-mac.sh $FEDORA_USER"
command -v sshpass >/dev/null 2>&1 || die "brew install hudochenkov/sshpass/sshpass"

bash "$(dirname "$0")/setup-remote-mac.sh" "$FEDORA_USER" >/dev/null

copy_to() {
  local target="$1"
  local label="$2"
  printf 'Пробую %s (%s)…\n' "$label" "$target"
  if sshpass -p "$FEDORA_PASSWORD" ssh-copy-id -i "$KEY" -o ConnectTimeout=5 \
    -o StrictHostKeyChecking=accept-new \
    "${FEDORA_USER}@${target}" 2>/dev/null; then
    printf '[ok] ключ установлен через %s\n' "$label"
    return 0
  fi
  return 1
}

printf '=== bootstrap SSH key → Fedora ===\n\n'

copy_to "$FEDORA_BT_IP" "BT PAN" || \
copy_to "$FEDORA_IP" "hotspot IP" || \
copy_to "$FEDORA_HOST" "mDNS" || \
die "не удалось подключиться — см. REMOTE_ACCESS.md (BT PAN или отключить AP isolation)"

printf '\nПроверка:\n'
bash "$(dirname "$0")/connect-fedora.sh" -- 'echo ok && hostname'
