#!/bin/sh

DEVICE_UID_FILE="/opt/extparam/device_uid"
EXPECTED_DEVICE_UID_STRING_SIZE=12

CPU_UID_LOW=$(cat /sys/fsl_otp/HW_OCOTP_CFG0 | cut -d 'x' -f2)
CPU_UID_HIGH=$(cat /sys/fsl_otp/HW_OCOTP_CFG1 | cut -d 'x' -f2)

ME="[sync-uid.sh]"

# We already had one device which didn't return anything from HW_OCOTP_CFG registers.
if [ -z "$CPU_UID_LOW" ] || [ -z "$CPU_UID_HIGH" ]
then
  logger -s "$ME Failed to retrieve a valid Device UID from hardware!"
  exit 1
fi

while [ ${#CPU_UID_LOW} -lt 8 ]
do
  CPU_UID_LOW="0${CPU_UID_LOW}"
done

while [ ${#CPU_UID_HIGH} -lt 8 ]
do
  CPU_UID_HIGH="0${CPU_UID_HIGH}"
done

EXPECTED_DEVICE_UID="${CPU_UID_HIGH:0:8}${CPU_UID_LOW:0:4}"

DEVICE_UID=""
if [ -r "${DEVICE_UID_FILE}" ]
then
  DEVICE_UID=$(cat ${DEVICE_UID_FILE})
fi

if ! [ "${EXPECTED_DEVICE_UID}" = "${DEVICE_UID}" ]
then
  logger -s "$ME Device UID should be: ${EXPECTED_DEVICE_UID} but is: ${DEVICE_UID}"
  printf "%s\\n" "${EXPECTED_DEVICE_UID}" > "${DEVICE_UID_FILE}"
else
  logger -s "$ME ${DEVICE_UID_FILE} is in sync with hardware."
fi

exit 0
