#!/usr/bin/env bash
# Mac: найти Fedora в сети хотспота.
#   bash docs/old_mac/scripts/discover-fedora.sh
set -euo pipefail

SUBNET=""
IFACE="en0"

wifi_ip() {
  ifconfig "$IFACE" 2>/dev/null | awk '/inet / {print $2; exit}'
}

IP="$(wifi_ip || true)"
[ -n "$IP" ] || { printf 'Wi-Fi IP не найден на %s\n' "$IFACE"; exit 1; }

SUBNET="$(printf '%s\n' "$IP" | awk -F. '{print $1"."$2"."$3}')"
printf 'Mac Wi-Fi: %s (подсеть %s.0/24)\n\n' "$IP" "$SUBNET"

# mDNS
printf '%s\n' '--- mDNS ---'
for name in fedora.local fedora; do
  FIP=""
  if command -v dscacheutil >/dev/null 2>&1; then
    FIP="$(dscacheutil -q host -a name "$name" 2>/dev/null | awk '/ip_address:/ {print $2; exit}')"
  fi
  [ -n "$FIP" ] || FIP="$(ping -c 1 -t 1 "$name" 2>/dev/null | sed -n 's/.*(\([0-9.]*\)).*/\1/p' | head -1)"
  if [ -n "$FIP" ]; then
    printf '%s → %s\n' "$name" "$FIP"
    if ping -c 1 -W 1000 "$FIP" >/dev/null 2>&1; then
      printf '  ping: ok\n'
    else
      printf '  ping: FAIL (вероятна изоляция клиентов хотспота)\n'
    fi
    if nc -z -w 2 "$FIP" 22 2>/dev/null; then
      printf '  ssh:22: open\n'
    else
      printf '  ssh:22: closed/unreachable\n'
    fi
    if nc -z -w 2 "$FIP" 3389 2>/dev/null; then
      printf '  rdp:3389: open\n'
    else
      printf '  rdp:3389: closed/unreachable\n'
    fi
  fi
done

printf '%s\n' '--- ARP ---'
arp -a 2>/dev/null | grep "$SUBNET" | grep -v 'incomplete' || true

printf '%s\n' '--- Быстрый sweep (ssh:22) ---'
FOUND=0
for i in $(seq 1 254); do
  T="$SUBNET.$i"
  [ "$T" = "$IP" ] && continue
  nc -z -G 1 -w 1 "$T" 22 2>/dev/null && printf 'ssh open: %s\n' "$T" && FOUND=1
done
[ "$FOUND" -eq 0 ] && printf '(ни одного ssh:22 не найдено)\n'

printf '%s\n' '--- BT PAN fallback ---'
printf 'Проверка 172.20.99.1 (Fedora BT PAN)…\n'
if ping -c 1 -W 1000 172.20.99.1 >/dev/null 2>&1; then
  printf '  ping 172.20.99.1: ok\n'
else
  printf '  ping 172.20.99.1: нет (запустите setup-bt-pan-fedora.sh на Fedora)\n'
fi

printf '\nПодсказка: если ping FAIL но mDNS есть — отключите AP isolation на телефоне\n'
printf 'или используйте Bluetooth PAN: REMOTE_ACCESS.md §4\n'
