#!/bin/sh

# Copyright 2021 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.



echo "SOM Dashboard initialization"

ip=""
python_path=""
queryip() {
    echo -n "waiting for IP address."
    for i in {1..20}
    do
        echo -n "."
        ip=`ifconfig eth0 | grep -oP 'inet \d+\.\d+\.\d+\.\d+' | cut -d ' ' -f2`
        [ ! -z "$ip" ] && break
        sleep 2
    done
}

querypath() {
    echo -n "waiting for path"
    for i in {1..20}
    do
        echo -n "."
        python_path=`python3 -m site | grep packages |grep usr | sed 's/,//g' |sed 's/ //g'| sed 's/^.//;s/.$//'`
        [ ! -z "$python_path" ] && break
        sleep 2
    done
}

DAEMON="bokeh"
DAEMON_ARGS=""
PIDFILE="/var/run/${DAEMON}.pid"



start ()
{
 echo " Starting $DAEMON"
 queryip
 querypath
 if [ -z $ip ] || [ -z $python_path ]; then
     echo " TIMEOUT cant find ip addr or python path"
     exit 1
 else
      DAEMON_ARGS=" serve --show --allow-websocket-origin=$ip:5006 $python_path/som-dashboard/"
      echo "start-stop-daemon -S -m -p $PIDFILE -x $DAEMON -- $DAEMON_ARGS"
      start-stop-daemon -S -m -p $PIDFILE -x $DAEMON -- $DAEMON_ARGS&
      echo " SOM Dashboard will be running at http://$ip:5006/som-dashboard "
 fi
}
stop ()
{
 echo " Stoping $DAEMON"
 # start-stop-daemon -K -x $DAEMON
 start-stop-daemon -K -q -p $PIDFILE

}
restart()
{
 stop
 start
}
[ -e $DAEMON ]
 case "$1" in
     start)
	 start; ;;
     stop)
	 stop; ;;
     restart)
	 restart; ;;
     *)
	 echo "Usage: $0 {start|stop|restart}"
	 exit 1
 esac
exit $?
