#!/bin/sh
# Load ipmodule-functions for logging functions
. /opt/gira/share/devicestack/ipmodule-vars
. /opt/gira/share/devicestack/ipmodule-functions

STKNX_FLASH_TOOL=/opt/gira/bin/stknxflash
STKNX_FLASH_TOOL_LOCKFILE=/opt/extparam/stknxflash.lock
STKNX_FLASH_LOG_CONFIG_FILE=/opt/gira/etc/stknx/stknxflash-log4cplus.prop
STKNX_FLASH_ADDITIONAL_ARGS_FILE=/opt/gira/etc/stknx/stknxflash-additional-args
STKNX_FIRMWARE=/opt/gira/share/knxstack/stm/StKnxLinkLayer.bin

if [ -e ${STKNX_FLASH_ADDITIONAL_ARGS_FILE} ]
then
{
  STKNX_FLASH_ADDITIONAL_ARGS=$(cat ${STKNX_FLASH_ADDITIONAL_ARGS_FILE})
}
fi

me="[$(printf $0 | xargs basename)]"
case "$1" in
  start)
    # Set reset pin to input (otherwise the STM32 won't be able to reset itself)
    echo "3" > /sys/class/gpio/export
    echo "in" > /sys/class/gpio/gpio3/direction
    log ${me} "Check/update STM32 firmware ..."
    # Check if firmware file and programmer are present.
    if [ -e ${STKNX_FLASH_TOOL} ] &&  [ -e ${STKNX_FIRMWARE} ]
    then
      # Start the program process.
      ${STKNX_FLASH_TOOL} --binary ${STKNX_FIRMWARE} --log_config_file ${STKNX_FLASH_LOG_CONFIG_FILE} --lock_file ${STKNX_FLASH_TOOL_LOCKFILE} ${STKNX_FLASH_ADDITIONAL_ARGS}
      log ${me} "done."
    else
      log_error ${me} "failed."
    fi
    ;;
  stop)
    ;;
  *)
    printf "Usage: %s (start|stop)\\n" "$0"
    exit 1
esac

exit 0
