#!/bin/sh

STKNX_FLASH_TOOL=/opt/gira/bin/stknxflash
STKNX_FIRMWARE=/opt/gira/share/knxstack/stm/StKnxLinkLayer.bin
STKNX_FLASH_TOOL_LOGFILE=/var/log/stknxflash.log
STKNX_FLASH_TOOL_LOCKFILE=/opt/extparam/stknxflash.lock
STKNX_LOG_CONFIG_FILE=/opt/gira/etc/stknx/stknx-log4cplus.prop

# Load ipmodule variables
. /opt/gira/share/devicestack/ipmodule-vars
STKNX_START_SCRIPT=/opt/gira/bin/start-stknx.sh
START_STKNX_PIDFILE="/var/run/start-stknx.pid"

trapFunction()
{
  trap - SIGHUP SIGINT SIGTERM
  kill $PID
  exit 0
}

trap trapFunction SIGHUP SIGINT SIGTERM

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
    # 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_LOG_CONFIG_FILE} --lock_file ${STKNX_FLASH_TOOL_LOCKFILE}
      printf "done.\\n"
    else
      printf "failed.\\n"
    fi
    printf "${me} Starting stknx ... "
    ${STKNX_START_SCRIPT} &
    printf "%s\\n" "$!" > ${START_STKNX_PIDFILE}
    printf "%s\\n" "$!"

    # wait little bit to be sure the stknx driver is up
    usleep 1000000
    printf "done.\\n"
    # Set KNX Traffic LED on to prevent all LEDs are deaktivated for a longer time priod
    # indicating the device is still alive
    printf "%s Set KNX Traffic LED on ... " "${me}"
    printf "1\\n" > /sys/class/leds/knx/brightness
    printf "done.\\n"
    ;;
  stop)
    printf "Stopping start-stknx ... "
    if start-stop-daemon --stop --quiet --pidfile ${START_STKNX_PIDFILE}
    then
      printf "done.\\n"
    else
      printf "failed.\\n"
    fi
    printf "Stopping stknx ... "
    ;;
  *)
    printf "Usage: %s (start|stop)\\n" "$0"
    exit 1
esac

exit 0
