#!/bin/bash -e

TEMPDIR=$(mktemp -d -p /tmp)
DESTDIR="/lib/firmware/brcm/"

SOURCE_URL[0]="https://github.com/RPi-Distro/firmware-nonfree/raw/master/brcm/brcmfmac43456-sdio.txt"
SOURCE_URL[1]="https://github.com/RPi-Distro/firmware-nonfree/raw/master/brcm/brcmfmac43456-sdio.bin"
SOURCE_URL[2]="https://github.com/RPi-Distro/firmware-nonfree/raw/master/brcm/brcmfmac43456-sdio.clm_blob"
SOURCE_URL[3]="https://github.com/RPi-Distro/bluez-firmware/raw/master/broadcom/BCM4345C5.hcd"
SOURCE_URL[4]="https://github.com/RPi-Distro/bluez-firmware/raw/master/broadcom/BCM43430A1.hcd"

cleanup()
{
	echo "Removing $(basename ${0}) temporary files..."
	rm -rf "$TEMPDIR"
}

trap cleanup EXIT INT HUP

# usage message
usage() {
	echo "
The tool will download the brcm firmware from a hardcoded URL
and copy it to the /lib/firmware/brcm directory.
Usage:

$(basename ${0})
Download and copy firmware

$(basename ${0}) --help
Print this message
"
}

if [ "$1" == "--help" ]
then
	usage
	exit 0
fi

if [ "$1" != "" ]
then
	echo "Unrecognized option: $1"
	usage
	exit 1
fi

# ensure sudo user
if [ "$(whoami)" != "root" ]
then
	echo "Error: This script requires 'sudo' privileges in order to copy firmware."
	exit 1
fi

ask_user()
{
	echo "
The following files will be downloaded and
written to the /lib/firmware/brcm directory:
"
	for i in "${SOURCE_URL[@]}"
	do
		echo "${i}"
	done
	echo "
Would you like to continue? [Yes/No] "
	read PROCEED
	case "$PROCEED" in
		[Yy][Ee][Ss])
			;;
		*)
			echo "User exit, no files written."
			exit 0
			;;
	esac
}

download_files()
{
	for i in "${SOURCE_URL[@]}"
	do
		wget --tries=10 "${i}" -P "${TEMPDIR}"
	done
}

copy_files()
{
	mkdir -p "${DESTDIR}"
	cd "${TEMPDIR}"
	cp -- * "${DESTDIR}"
}

main()
{
	ask_user
	download_files
	copy_files
}

main
