#!/bin/sh

# Please note that we do format the SPI NOR flash if it is filled with zeros.
# The devices leave the factory in this state which prevents /opt/extparam
# to be mounted and used. To enable its use for devices which have already
# been sold, too, this init script now checks for the condition and formats
# the flash to jffs2 and mounts the extparam properly.
# The partition is then populated by the S83devcfg script; fddp and fdsk are
# missing though. They both need to be set with the commissioning tool.
#
# This hassle is done only for the KNX/IP-Router secure, which needs the keys
# stored in /opt/extparam.

# checks if the extparam partition is all zeros
check_for_zeros()
{
  dump=$(od /dev/mtdblock6 | head -n3)
  zero_image="0000000 000000 000000 000000 000000 000000 000000 000000 000000
*
10000000"
  if [ "${dump}" = "${zero_image}" ]; then
    return 0
  else
    return 1
  fi
}

# Load ipmodule variables
. /opt/gira/share/devicestack/ipmodule-vars

case "$1" in
        start)
		/bin/mount /opt/extparam
		if ! [ $? -eq 0 ]; then
		  if check_for_zeros; then
		    printf "SPI flash contains only zeros, formatting device...\\n"
		    flash_erase --jffs2 --quiet /dev/mtd6 0 0
		    /bin/mount /opt/extparam
		  fi
		fi

		sync && /opt/gira/bin/update-md5sum-of-extparam && sync
                ;;
        stop)
                sync && /opt/gira/bin/update-md5sum-of-extparam && sync
                /bin/umount /opt/extparam
		;;
        *)
                printf "Usage: %s (start|stop)\\n" "$0"
                exit 1
esac

exit 0
