#!/bin/sh

device_name="biosmart"
device_dir=/home/root/$device_name
app=$(basename $(readlink $device_dir/app))
device=$device_dir/$app
device_arg="-platform eglfs"
device_pid=/var/run/biosmart.pid
db=/home/root/biosmart.db
export PATH=$PATH:/sbin

device_start() {
    # clear *.lock files
    find /etc/prosoft-biometrics/ -name '*.lock' -exec rm -f {} \;

    cd /home/root
    mkdir -p /home/root/tmp
    export SQLITE_TMPDIR=/home/root/tmp
    export QT_LOGGING_CONF=/home/root/$device_name/log_rules.ini
    export LD_LIBRARY_PATH=/usr/local/Qt-5.8/lib:/home/root/$device_name
    export XDG_CONFIG_HOME=/etc/

    ulimit -c unlimited ; sysctl -w kernel.core_pattern=/home/root/core.dump

    device_stop

    echo "Try to starting $device_name daemon....."
    start-stop-daemon --start --quiet --pidfile $device_pid --make-pidfile --exec $device -- $device_arg &
    sleep 1
    echo -n "Check $device_name daemon after starting"
    wait_pid=`cat $device_pid`
    real_pid=`pidof $device`
    if [ "$wait_pid" == "$real_pid" ]; then
        echo ".....[OK]"
        retval=0
    else
        echo "...[FAIL]"
        retval=1
    fi
    return "$retval"
}

start_watchdog() {
    if [ `pidof watchdog` > 0 ]; then
        echo -n "Stopping watchdog"
        kill -9 `pidof watchdog`
        echo ".....[OK]"
    fi

    sleep 3
    echo -n "Starting watchdog..."
    $device_dir/watchdog &
    sleep 1
    if [ `pidof watchdog` > 0 ]; then
        echo ".....[OK]"
    else
        echo "...[FAIL]"
    fi
}

try_restore() {
    cd /home/root
    echo -n "Try restore"
    link_=`readlink $device_name`
    dirs_=`ls | grep $device_name.ver.`
    old_=

    for x in $dirs_
    do
        if [ "$x" != "$link_" ]; then
            old_=$x
        fi
    done

    if [ "$old_" == "" ]; then
        echo "...[FAIL]"
        start_watchdog
        exit 1
    fi

    rm -f $device_name
    ln -s $old_ $device_name
    echo ".....[OK]"

    device_start
    start_watchdog
    exit 0
}

device_stop() {
    if [ `pidof $device` > 0 ]; then
        start-stop-daemon --stop --quiet --pidfile $device_pid
        sleep 3
    fi
    if [ -f $device_pid ]; then
        rm -f $device_pid
    fi
    if [ `pidof $device` > 0 ]; then
        kill -9 `pidof $device`
    fi
    #ps | grep biosmart | grep -v grep
}

#test -x "$device" || try_restore

case "$1" in
  start)
    device_start
    start_watchdog
    ;;
  stop)
    echo -n "Stopping watchdog"
    if [ `pidof watchdog` > 0 ]; then
        kill -9 `pidof watchdog`
        echo ".....[OK]"
    else
        echo "...[Stopped]"
    fi
    echo -n "Stopping $device_name daemon"
    device_stop
    echo ".....[OK]"
    ;;
  restart)
    $0 stop
    sleep 1
    $0 start
    ;;
  reload)
    echo "Reload biosmart..."
    device_stop
    device_start
    echo "...[OK]"
    ;;
  *)
    echo "Usage: /etc/init.d/$device_name {start|stop|restart}"
    exit 1
esac

exit 0
