#!/bin/bash

#
# This fault script saves the current temperature and date to the
# U-Boot environment on ARM platforms.
#
# Arguments: arg1 = fault code, arg2 = fault value
#
# Currently only the overtemperature fault is handled, where the
# value is the current temperature.
#

fault="$1"
value="$2"

# Only ARM patforms, with U-Boot, are currently supported.
[ "$HOSTTYPE" != "arm" ] && exit 0

# The name of the U-Boot environment variable to save the log
UVARNAME="templog"
# The maximum length of the log
MAXLEN=2000
# The length to truncate the log to when over max length
TRUNCLEN=1800

# Get the current log from U-Boot, if any
templog="$(fw_printenv -n $UVARNAME 2>/dev/null)"
if [ $? -ne 0 ]; then
    templog=""
elif [ "${#templog}" -gt $MAXLEN ]; then
    templog="${templog:0:TRUNCLEN}"
fi

# Entry is value and date (ISO-8601 UTC) to log
nlog="${value}@$(date -u +'%Y-%m-%dT%H:%M:%SZ')"

# Prepend entry to log, entries are comma separated
if [ -n "$templog" ]; then
    templog="${nlog},${templog}"
else
    templog="${nlog}"
fi

# Save the new log to U-Boot environment
fw_setenv $UVARNAME "$templog"
