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

STKNX_START_SCRIPT=/opt/gira/bin/start-stknx.sh
START_STKNX_PIDFILE="/var/run/start-stknx.pid"

trapFunction()
{
  trap - SIGHUP SIGINT SIGTERM
  PID=$(cat ${START_STKNX_PIDFILE})
  log ${me} "Stopping ${STKNX_START_SCRIPT} PID=${PID} ... "
  kill ${PID}
  exit 0
}

trap trapFunction SIGHUP SIGINT SIGTERM

me="[$(printf $0 | xargs basename)]"
case "$1" in
  start)
    log ${me} "Starting ${STKNX_START_SCRIPT} ... "
    ${STKNX_START_SCRIPT} &
    printf "%s\\n" "$!" > ${START_STKNX_PIDFILE}
    log ${me} "PID=$!"

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

exit 0
