#!/usr/bin/env bash
# Mac: ключ SSH + ssh config для Fedora MacBook.
#   bash docs/old_mac/scripts/setup-remote-mac.sh [fedora_user]
set -euo pipefail

OLD_MAC="$(cd "$(dirname "$0")/.." && pwd)"
FEDORA_USER="${1:-p}"
KEY="$HOME/.ssh/id_ed25519_fedora"
KEY_PUB="${KEY}.pub"
SSH_CONFIG="$HOME/.ssh/config"
DELIVERABLE="$OLD_MAC/deliverable"
PUBKEY_EXPORT="$DELIVERABLE/mac_pubkey.txt"

mkdir -p "$DELIVERABLE" "$HOME/.ssh"
chmod 700 "$HOME/.ssh"

if [ ! -f "$KEY" ]; then
  ssh-keygen -t ed25519 -f "$KEY" -N "" -C "mac-fedora-remote-$(hostname -s)"
  printf 'Создан ключ: %s\n' "$KEY"
fi

cp "$KEY_PUB" "$PUBKEY_EXPORT"
chmod 644 "$PUBKEY_EXPORT"

MARK_BEGIN="# --- old_mac fedora-mbp (local_machine) ---"
MARK_END="# --- end old_mac fedora-mbp ---"
BLOCK=$(cat <<EOF
$MARK_BEGIN
Host fedora-mbp old-mac-fedora fedora
  User $FEDORA_USER
  IdentityFile $KEY
  IdentitiesOnly yes
  StrictHostKeyChecking accept-new
  # Hotspot LAN (mDNS)
  HostName fedora.local
  # BT PAN: Fedora = 172.20.99.1
  # HostName 172.20.99.1

Host fedora-mbp-bt
  HostName 172.20.99.1
  User $FEDORA_USER
  IdentityFile $KEY
  IdentitiesOnly yes
  StrictHostKeyChecking accept-new
$MARK_END
EOF
)

if [ -f "$SSH_CONFIG" ] && grep -q "$MARK_BEGIN" "$SSH_CONFIG"; then
  awk -v b="$MARK_BEGIN" -v e="$MARK_END" '
    $0==b {skip=1; next}
    $0==e {skip=0; next}
    !skip {print}
  ' "$SSH_CONFIG" >"$SSH_CONFIG.tmp"
  mv "$SSH_CONFIG.tmp" "$SSH_CONFIG"
fi

printf '\n%s\n' "$BLOCK" >>"$SSH_CONFIG"
chmod 600 "$SSH_CONFIG"

printf '\n=== Mac готов ===\n'
printf 'Ключ: %s\n' "$KEY"
printf 'Публичный ключ (для Fedora): %s\n' "$PUBKEY_EXPORT"
printf 'SSH config: Host fedora-mbp | fedora-mbp-bt\n\n'
printf 'Дальше:\n'
printf '  1. Пересобрать архив: bash %s/build-remote-access-archive.sh\n' "$(dirname "$0")"
printf '  2. Отправить на Fedora по BT: bash %s/send-to-fedora-bluetooth.sh\n' "$(dirname "$0")"
printf '  3. На Fedora: sudo bash setup-ssh-fedora.sh %s\n' "$FEDORA_USER"
printf '  4. С Mac: bash %s/connect-fedora.sh\n' "$(dirname "$0")"
