#!/usr/bin/env bash
# Mac: настроить IP на Bluetooth PAN к Fedora (после Connect к NAP).
#   bash docs/old_mac/scripts/setup-bt-pan-mac.sh
set -euo pipefail

MAC_IP="${MAC_IP:-172.20.99.2}"
FEDORA_IP="${FEDORA_IP:-172.20.99.1}"
PREFIX=24

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

# Найти bnep/pan интерфейс
IFACE=""
for cand in bnep0 pan0 bridge100; do
  if ifconfig "$cand" >/dev/null 2>&1; then
    IFACE="$cand"
    break
  fi
done

if [ -z "$IFACE" ]; then
  IFACE="$(ifconfig -l | tr ' ' '\n' | grep -E '^bnep|^pan' | head -1)"
fi

[ -n "$IFACE" ] || die "нет bnep/pan интерфейса — сначала на Fedora: sudo bash setup-bt-pan-fedora.sh, затем Mac Bluetooth → fedora → Connect (Network)"

printf 'Интерфейс: %s\n' "$IFACE"

sudo ifconfig "$IFACE" "$MAC_IP" netmask 255.255.255.0 up
sudo route add -host "$FEDORA_IP" -interface "$IFACE" 2>/dev/null || true

printf '\nПроверка ping %s …\n' "$FEDORA_IP"
if ping -c 2 -W 1000 "$FEDORA_IP"; then
  printf '\n[ok] L2/L3 связь Mac ↔ Fedora по BT PAN\n'
  printf 'SSH: bash docs/old_mac/scripts/connect-fedora.sh\n'
else
  printf '\n[!] ping не прошёл — повторите Connect к fedora в Bluetooth\n'
  exit 1
fi
