#!/bin/sh

PROGNAME=$0

usage() {
cat << EOF >&2
Usage: $PROGNAME [-rh]

Endless OS utility to do RPi secure boot provisioning with rpiboot.
Note: This is irreversible changes to the OTP of the RPi device!

Options:
    -r The Raspberry Pi has done RPi secure boot provisioning before. Do the
       provisioning again.
    -h Show this help usage.
EOF
  exit 1
}

provisioned=0
while getopts rh option; do
   case "${option}" in
   r) provisioned=1
      ;;
   h) usage
      ;;
   *) echo "Unknown argument \"${option}\""
      usage
      ;;
   esac
done

TMPDIR=$(mktemp -d)
cp /usr/share/rpiboot/secure-boot-recovery5-signed/* ${TMPDIR}/
trap 'rm -rf ${TMPDIR}' EXIT

# Lock the device to the public key in the EEPROM by storing the sha256 hash of
# the public key in OTP.
sed -i 's/^#program_pubkey=1$/program_pubkey=1/' ${TMPDIR}/config.txt

# The Pi will disconnect USB and reboot after the flashing the firmware.
sed -i 's/^#recovery_reboot=1$/recovery_reboot=1/' ${TMPDIR}/config.txt

if [ ${provisioned} != 1 ]; then
  # Must use unsigned recovery.bin image on a fresh board without secure-boot
  # enabled. The original bootcode5.bin is signed.
  cp ${TMPDIR}/recovery.original.bin ${TMPDIR}/bootcode5.bin
fi

sudo rpiboot -d ${TMPDIR}
