#!/usr/bin/env bash
# Собрать архив для передачи на Fedora MacBook.
#   bash docs/old_mac/scripts/build-delivery-archive.sh
set -euo pipefail

OLD_MAC="$(cd "$(dirname "$0")/.." && pwd)"
STAGE="${TMPDIR:-/tmp}/fedora-bcm4322-wifi-fix-$$"
ARCHIVE="$OLD_MAC/deliverable/fedora-bcm4322-wifi-fix.tar.gz"
PKG="fedora-bcm4322-wifi-fix"

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

[ -f "$OLD_MAC/bundle/bcm4322-offline-bundle/b43/ucode16_mimo.fw" ] \
  || die "нет firmware — сначала: bash $OLD_MAC/scripts/download-bcm4322-offline-bundle.sh"

cleanup() { rm -rf "$STAGE"; }
trap cleanup EXIT

rm -rf "$STAGE"
mkdir -p "$STAGE/$PKG/bundle"
cp -a "$OLD_MAC/bundle/bcm4322-offline-bundle" "$STAGE/$PKG/bundle/"
cp "$OLD_MAC/scripts/install-bcm4322-firmware-fedora.sh" "$STAGE/$PKG/"
cp "$OLD_MAC/scripts/prepare-receive-fedora.sh" "$STAGE/$PKG/"
cp "$OLD_MAC/RUNBOOK.md" "$STAGE/$PKG/"

cat >"$STAGE/$PKG/INSTALL.txt" <<'EOF'
Fedora 43 — BCM4322 Wi-Fi fix (offline)
========================================

1. Распаковать:
   tar xzf fedora-bcm4322-wifi-fix.tar.gz
   cd fedora-bcm4322-wifi-fix

2. Установить firmware (root):
   sudo bash install-bcm4322-firmware-fedora.sh

3. Перезагрузить:
   sudo reboot

4. Подключиться к Wi-Fi:
   nmcli device wifi list
   nmcli device wifi connect "SSID" password "пароль"

5. Проверка:
   ls -la /lib/firmware/b43/ucode16_mimo.fw
   sudo dmesg | grep -i b43
   nmcli device

Подробности: RUNBOOK.md в этом архиве.
EOF

mkdir -p "$OLD_MAC/deliverable"
tar czf "$ARCHIVE" -C "$STAGE" "$PKG"
SHA="$(shasum -a 256 "$ARCHIVE" | awk '{print $1}')"
SIZE="$(stat -f%z "$ARCHIVE" 2>/dev/null || stat -c%s "$ARCHIVE")"

cat >"$OLD_MAC/deliverable/MANIFEST.txt" <<EOF
Package: fedora-bcm4322-wifi-fix.tar.gz
Built: $(date -u +%Y-%m-%dT%H:%M:%SZ)
Size: ${SIZE} bytes
SHA256: ${SHA}
Target: Fedora 43, MacBook Pro Intel, BCM4322 / b43
EOF

printf 'Архив: %s\n' "$ARCHIVE"
printf 'Размер: %s bytes\n' "$SIZE"
printf 'SHA256: %s\n' "$SHA"
