#!/bin/sh

target_device="/dev/mmcblk0"
bootloader_file="u-boot-dtb.imx"
# KFR is this the valid bootloader script?
bootscript_file="u-boot.scr"

filesize=$(ls -l $bootloader_file | awk '{ print $5 }')
installed_checksum=$(dd if="$target_device"  bs=1 count="$filesize"  skip=1024 | md5sum | cut -d " " -f1)
bootloader_checksum=$(md5sum "$bootloader_file" | cut -d " " -f1)

printf "Installed bootloader checksum: %s\\n" "$installed_checksum"
printf "Devicepackage's bootloader checksum: %s\\n" "$bootloader_checksum"

if [ "$installed_checksum" = "$bootloader_checksum" ]; then
  printf "Do not exchange bootloader\\n"
else
  printf "Exchanging bootloader...\\n"
  dd if=${bootloader_file} bs=1K seek=1 of=${target_device}
  if [ "$?" -ne 0 ]; then
    printf "Exchanging the bootloader failed!\\n"
    exit 1
  fi
  printf "Bootloader successfully exchanged!\\n"
fi


if [ -e /opt/extparam/${bootscript_file} ]; then
  # if md5 file for boot script does not exist, create it.
  if ! [ -e /opt/extparam/${bootscript_file}.md5 ]; then
    (cd /opt/extparam && md5sum ${bootscript_file} > ${bootscript_file}.md5)
  fi

  installed_bootscript_md5=$(head -n 1 /opt/extparam/${bootscript_file}.md5 | cut -d " " -f 1)
  contained_bootscript_md5=$(md5sum ${bootscript_file} | cut -d " " -f 1)

  printf "Installed U-Boot script hash is %s\\n" "${installed_bootscript_md5}"
  printf "Contained U-Boot script hash is %s\\n" "${contained_bootscript_md5}"

  # check if md5 sum has been processed successfully
  if [ -z "${contained_bootscript_md5}" ]; then
    printf "md5 of ${bootscript_file} is empty\\n"
    exit 1 
  fi

  # check if hashes differ and overwrite
  if ! [ "${installed_bootscript_md5}" = "${contained_bootscript_md5}" ];   then
    printf "Overwriting U-Boot script now.\\n"
    cp ${bootscript_file} /opt/extparam/${bootscript_file}
    md5sum ${bootscript_file} > /opt/extparam/${bootscript_file}.md5
  else
    printf "No need to overwrite U-Boot script.\\n"
  fi
else # Commissioning does not ship the bootscript.
  cp ./${bootscript_file} /opt/extparam/${bootscript_file}
  #cp ./boot/${bootscript_file}.md5 /opt/extparam/${bootscript_file}.md5
fi


exit 0
