#!/bin/bash
#################################################################################
# Script : get-firmware.sh
# Purpose: Download and pack firmware for the bcm2711 SoC.
#          Hardware Models using this SoC:
#          * Raspberry Pi 4
# Author : Brenton Earl
#          Modifed by MoZes to re-pack the firmware due to size.
# Date...: Dec. 17, 2021
#################################################################################
#SVNR="1337"
#URL="https://github.com/RPi-Distro/firmware-nonfree/trunk/debian/config/brcm80211/"
#svn checkout -r $SVNR $URL

# Previous working version:
#https://archive.raspberrypi.org/debian/pool/main/b/bluez-firmware/bluez-firmware_1.2-4+rpt8_all.deb
#FW_BLUEZ=https://archive.raspberrypi.org/debian/pool/main/b/bluez-firmware/bluez-firmware_1.2-9+rpt3_all.deb
FW_BLUEZ=https://archive.raspberrypi.org/debian/pool/main/b/bluez-firmware/bluez-firmware_1.2-13+rpt1_all.deb
# Previous working version:
#FW_MAIN=https://archive.raspberrypi.org/debian/pool/main/f/firmware-nonfree/firmware-brcm80211_20230625-2+rpt2_all.deb
FW_MAIN=https://archive.raspberrypi.org/debian/pool/main/f/firmware-nonfree/firmware-brcm80211_20241210-1+rpt2_all.deb

CWD=$PWD
TMP=/tmp/fw-assets
OUT=$CWD/assets

rm -rf $TMP $OUT
mkdir -p $OUT $TMP/{tree/usr/doc,unpack}

cd $TMP/unpack
wget $FW_BLUEZ
ar -x bluez-firmware*.deb
tar xf data.tar.?z -C $TMP/tree || exit 1

rm -rf $TMP/unpack
mkdir -p $TMP/unpack
cd $TMP/unpack
wget $FW_MAIN
ar -x firmware-brcm80211*.deb
tar xf data.tar.?z -C $TMP/tree || exit 1
# Clean up:
# We'll keep the changelogs though.
cd $TMP/tree

# Move firmware from /usr/lib -> /lib which is where it used to be:
mkdir -p lib
mv -fv usr/lib/firmware lib/
rmdir usr/lib

find . -type f -name README.Debian -print0 | xargs -0 rm -rfv
# Move docs into Slackware location:
mv -fv usr/share/doc usr/
rm -rf usr/share/{bug,metainfo}
rmdir usr/share

# Pack:
echo "Packing..."
tar -Ixz -cf $OUT/fw-bcm2711.tar.xz .
rm -rf $TMP
