#!/usr/bin/env bash
# Скачать и собрать firmware b43 для BCM4322 (запуск на Mac с интернетом).
#   bash docs/old_mac/scripts/download-bcm4322-offline-bundle.sh
set -euo pipefail

OLD_MAC="$(cd "$(dirname "$0")/.." && pwd)"
BUNDLE_DIR="$OLD_MAC/bundle/bcm4322-offline-bundle"
WORK="${TMPDIR:-/tmp}/bcm4322-build-$$"
WL_VERSION="6.30.163.46"
WL_TARBALL="broadcom-wl-${WL_VERSION}.tar.bz2"
WL_OBJECT="broadcom-wl-${WL_VERSION}.wl_apsta.o"
WL_URL="https://web.archive.org/web/2023/https://www.lwfinger.com/b43-firmware/${WL_TARBALL}"

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

command -v b43-fwcutter >/dev/null 2>&1 || die "brew install b43-fwcutter"
command -v curl >/dev/null 2>&1 || die "curl не найден"

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

mkdir -p "$WORK" "$BUNDLE_DIR"
cd "$WORK"

if [ ! -s "$WL_TARBALL" ]; then
  printf 'Скачиваю %s …\n' "$WL_URL"
  curl -fsSL --max-time 180 -o "$WL_TARBALL" "$WL_URL"
fi
file "$WL_TARBALL" | grep -qi bzip2 || die "скачанный файл не bzip2"

tar xjf "$WL_TARBALL"
[ -f "$WL_OBJECT" ] || die "нет $WL_OBJECT в архиве"

rm -rf "$WORK/fw-out"
mkdir -p "$WORK/fw-out"
b43-fwcutter -w "$WORK/fw-out" "$WL_OBJECT"
[ -f "$WORK/fw-out/b43/ucode16_mimo.fw" ] || die "нет ucode16_mimo.fw"

rm -rf "$BUNDLE_DIR/b43"
cp -a "$WORK/fw-out/b43" "$BUNDLE_DIR/"

COUNT="$(find "$BUNDLE_DIR/b43" -type f | wc -l | tr -d ' ')"
SHA_UC="$(shasum -a 256 "$BUNDLE_DIR/b43/ucode16_mimo.fw" | awk '{print $1}')"

cat >"$BUNDLE_DIR/MANIFEST.txt" <<EOF
BCM4322 b43 firmware offline bundle
Built: $(date -u +%Y-%m-%dT%H:%M:%SZ)
Source: broadcom-wl-${WL_VERSION} via b43-fwcutter
Files: ${COUNT}
SHA256 b43/ucode16_mimo.fw: ${SHA_UC}
EOF

printf 'Firmware: %s файлов\n' "$COUNT"
bash "$(dirname "$0")/build-delivery-archive.sh"
