#!/bin/sh

# Convenience script for updating the rpi-eeprom updater via a git
# clone instead of apt install.

# For test & debug only.

set -e

script_dir="$(cd "$(dirname "$0")" && pwd)"

die() {
  echo "$@" >&2
  exit 1
}

FIRMWARE_DIR="${script_dir}/../firmware"
CONFIG="/etc/default/rpi-eeprom-update"

[ "$(id -u)" = "0" ] || die "$0 Must be run as root - try 'sudo $0 [-b]'"

# Clear out the old firmware
rm -rf /lib/firmware/raspberrypi/bootloader
rm -rf /lib/firmware/raspberrypi/bootloader-2711
rm -rf /lib/firmware/raspberrypi/bootloader-2712

mkdir -p /lib/firmware/raspberrypi/bootloader-2711
rsync -alv "${FIRMWARE_DIR}-2711"/* /lib/firmware/raspberrypi/bootloader-2711 || echo "Failed"
mkdir -p /lib/firmware/raspberrypi/bootloader-2712
rsync -alv "${FIRMWARE_DIR}-2712"/* /lib/firmware/raspberrypi/bootloader-2712 || echo "Failed"

cp -fv "${script_dir}/../rpi-eeprom-config" /usr/bin
cp -fv "${script_dir}/../rpi-eeprom-digest" /usr/bin
cp -fv "${script_dir}/../rpi-eeprom-update" /usr/bin
rm -f /usr/bin/vl805

cp -fv "${script_dir}/../rpi-eeprom-update-default" /etc/default/rpi-eeprom-update

if [ "$1" = "-b" ]; then
   sed -i -e 's/^FIRMWARE_RELEASE_STATUS=.*/FIRMWARE_RELEASE_STATUS=beta/' "${CONFIG}"
fi
