#!/usr/bin/env bash
# Fedora: поднять Bluetooth PAN (NAP) для прямой сети Mac ↔ Fedora.
# Обходит изоляцию клиентов на хотспоте телефона.
#   sudo bash setup-bt-pan-fedora.sh
set -euo pipefail

PAN_IF="${PAN_IF:-pan0}"
PAN_IP="${PAN_IP:-172.20.99.1}"
PAN_CIDR="${PAN_CIDR:-24}"
MAC_BT_IP="${MAC_BT_IP:-172.20.99.2}"

die() { printf 'error: %s\n' "$*" >&2; exit 1; }
[ "$(id -u)" -eq 0 ] || die "sudo"

printf '=== Bluetooth PAN (Fedora = сервер) ===\n\n'

for pkg in bluez bluez-tools; do
  rpm -q "$pkg" >/dev/null 2>&1 || dnf install -y "$pkg" || true
done

command -v bt-network >/dev/null 2>&1 || die "нет bt-network (dnf install bluez-tools)"

systemctl start bluetooth
sleep 1

# Остановить старый NAP
bt-network -d nap 2>/dev/null || true
pkill -f "bt-network -s nap" 2>/dev/null || true
sleep 1

printf 'Запуск NAP на %s (%s/%s)…\n' "$PAN_IF" "$PAN_IP" "$PAN_CIDR"
bt-network -s nap "$PAN_IF" &
sleep 2

ip link set "$PAN_IF" up 2>/dev/null || true
ip addr flush dev "$PAN_IF" 2>/dev/null || true
ip addr add "${PAN_IP}/${PAN_CIDR}" dev "$PAN_IF"

printf '\n[ok] PAN сервер на Fedora\n'
printf '  Интерфейс: %s = %s/%s\n' "$PAN_IF" "$PAN_IP" "$PAN_CIDR"
printf '  Mac после подключения PAN: назначьте %s/24 на bnep0\n' "$MAC_BT_IP"
printf '    (или Mac Internet Sharing — см. REMOTE_ACCESS.md)\n\n'
printf 'На Mac:\n'
printf '  1. Bluetooth → fedora → Connect / «Сеть» / Network Access Point\n'
printf '  2. bash docs/old_mac/scripts/setup-bt-pan-mac.sh\n'
printf '  3. bash docs/old_mac/scripts/connect-fedora.sh\n'
