#!/bin/sh
# seed-broadcom-pool
# -----------------------------------------------------------------------------
# RUN ON THE BUILD VM during ISO prep (needs the LL/Ubuntu repo reachable).
#
# Seeds a small *local, offline* apt pool with the proprietary Broadcom Wi-Fi
# driver (broadcom-sta-dkms) and everything needed to build its `wl` module
# offline, so Lite Driver Manager can install it on a shipped/OEM laptop with
# NO internet. Pairs with the boot-hang blacklist (broadcom-ac-blacklist):
# clean boot out of the box, then one-click *offline* Wi-Fi via Lite Driver
# Manager.
#
# Opt-in per build: this only takes effect on ISOs where you run it. General
# ISOs that never run it carry no pool and no extra apt source. RE-RUN AFTER A
# KERNEL BUMP (the headers must match the shipped kernel), then rebuild the ISO.
# -----------------------------------------------------------------------------
set -e

POOL=/var/lib/linuxlite/broadcom-pool
SRC=/etc/apt/sources.list.d/linuxlite-broadcom-pool.sources
KVER="$(uname -r)"

[ "$(id -u)" = 0 ] || { echo "seed-broadcom-pool: run as root (sudo)." >&2; exit 1; }
command -v dpkg-scanpackages >/dev/null 2>&1 || {
    echo "seed-broadcom-pool: need dpkg-dev (dpkg-scanpackages). Install it first." >&2
    exit 1
}
command -v apt-ftparchive >/dev/null 2>&1 || {
    echo "seed-broadcom-pool: need apt-utils (apt-ftparchive). Install it first." >&2
    exit 1
}

echo ">> apt update, then downloading broadcom-sta-dkms + build closure for $KVER"
apt-get update
mkdir -p "$POOL"

# Download the driver plus what DKMS needs to build `wl` offline at install
# time. Only packages missing from this (build) system download — and since the
# build VM is the squashfs source, that's exactly what'll be missing in the
# target too. linux-headers must match the shipped kernel.
apt-get install -y --download-only \
    broadcom-sta-dkms dkms "linux-headers-$KVER" linux-libc-dev \
    gcc make binutils libc6-dev

cp -f /var/cache/apt/archives/*.deb "$POOL"/ 2>/dev/null || true

# Build a flat-repo index so apt can resolve it offline. The Release file makes
# apt fetch only what it lists (no Translation-en probing -> no "Err" noise in
# Lite Updates, which file:// sources would otherwise log for missing files).
( cd "$POOL" && dpkg-scanpackages -m . > Packages && gzip -9kf Packages \
    && apt-ftparchive release . > Release )

# Write the local, trusted, offline apt source (flat repo: Suites = ./).
cat > "$SRC" <<EOF
# Linux Lite offline Broadcom driver pool (seeded by seed-broadcom-pool).
# Lets Lite Driver Manager install broadcom-sta-dkms with no internet.
Types: deb
URIs: file:$POOL
Suites: ./
Trusted: yes
Architectures: amd64
EOF

apt-get update
echo ">> Seeded $(ls "$POOL"/*.deb 2>/dev/null | wc -l) .debs into $POOL"
echo ">> TEST: 'sudo apt-get -o Acquire::Languages=none install --no-download broadcom-sta-dkms'"
echo "         should succeed offline. Then rebuild the ISO."
