#!/bin/sh

# Display the running Raspberry Pi bootloader version.
#
# Reads the version information from device-tree to avoid adding a dependency on
# vcgencmd for bootloader updates.

set -e

EXIT_SUCCESS=0
EXIT_FAILED=2

# Location of the bootloader properties exported by the firmware via device-tree.
DT_BOOTLOADER=${DT_BOOTLOADER:-/proc/device-tree/chosen/bootloader}

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

# Read a big-endian device-tree integer property as a decimal number.
readDtInt() {
   printf "%d" "0x$(od "$1" -v -An -t x1 | tr -d ' \n')"
}

if [ ! -d "${DT_BOOTLOADER}" ]; then
   die "Bootloader version not available via device-tree (${DT_BOOTLOADER} not found)."
fi

build_ts_file="${DT_BOOTLOADER}/build-timestamp"
[ -f "${build_ts_file}" ] || die "${build_ts_file} not found."
build_ts=$(readDtInt "${build_ts_file}")

# First line is the build date in local time.
date -d "@${build_ts}" "+%Y/%m/%d %H:%M:%S"

# The version property is the bootloader git hash. The build variant (e.g.
# "release") is not exported via device-tree; released images are always
# "release" builds.
if [ -f "${DT_BOOTLOADER}/version" ]; then
   echo "version $(strings "${DT_BOOTLOADER}/version") (release)"
fi

echo "timestamp ${build_ts}"

if [ -f "${DT_BOOTLOADER}/update-timestamp" ]; then
   echo "update-time $(readDtInt "${DT_BOOTLOADER}/update-timestamp")"
fi

if [ -f "${DT_BOOTLOADER}/capabilities" ]; then
   printf "capabilities 0x%08x\n" "$(readDtInt "${DT_BOOTLOADER}/capabilities")"
fi

echo ""

exit ${EXIT_SUCCESS}
