#!/bin/sh
#/etc/init.d/jupyterlab-start: start jupyterlab daemon

### BEGIN INIT INFO
# Provides:          jupyter-lab
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: Start Jupyter Lab server as petalinux user
### END INIT INFO

OWNER="petalinux"
GROUP="petalinux"
HOME=`(cd ~petalinux && pwd) || echo 'none'`
NBDIR="${HOME}/notebooks"

DAEMON_PATH="/usr/bin/jupyter-lab"
DAEMON_ARGS="--no-browser --notebook-dir=$NBDIR"
DAEMON_NAME=`basename $DAEMON_PATH`
PIDFILE="/var/run/${DAEMON_NAME}.pid"

PATH=/bin:/usr/bin:/sbin:/usr/sbin

. /etc/init.d/functions

ip=""
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
}

log_begin_msg() {
    echo -n $*
}

log_end_msg() {
    if [ "$1" = "0" ]; then
        echo ' OK'
    else
        echo ' ERROR'
    fi
}

log_daemon_msg() {
    echo $*
}

log_progress_msg() {
    echo $*
}

test -x $DAEMON_PATH || exit 0

case "$1" in
    start)
        log_begin_msg "Starting $DAEMON_NAME server daemon... "
        queryip
        if [ -z $ip ]; then
            echo " TIMEOUT"
            exit 1
        else
            # Various jupter paths are incorrect if this daemon is run as part of the
            # init process. Override the directories with these environment variables.
            export JUPYTER_CONFIG_DIR="${HOME}/.jupyter"
            export JUPYTER_DATA_DIR="${HOME}/.local/share/jupyter"
            export JUPYTER_RUNTIME_DIR="${HOME}/.local/share/jupyter/runtime"
            export HOME="${HOME}"

            # check owner and group are valid
            id $OWNER > /dev/null 2>&1
            if [ "$?" = "1" ]; then echo "'$OWNER': no such owner... ERROR" ; exit 1 ; fi
            grep $GROUP /etc/group > /dev/null
            if [ "$?" = "1" ]; then echo "'$GROUP': no such group... ERROR" ; exit 1 ; fi

            # create nb dir if it doesn't exist
            if [ ! -d "$NBDIR" ] ; then install -o $OWNER -g $GROUP -d $NBDIR ; fi

            # start the daemon
            start-stop-daemon -S -c $OWNER:$GROUP -m -p $PIDFILE -x $DAEMON_PATH -- $DAEMON_ARGS --ip=$ip &
            log_end_msg $?
	fi
        ;;

    stop)
        log_begin_msg "Stopping $DAEMON_NAME server daemon..."
        start-stop-daemon -K -q -p $PIDFILE
        log_end_msg $?
        ;;

    restart)
        $0 force-reload
        ;;

    force-reload)
        log_daemon_msg "Restarting $DAEMON_NAME"
        $0 stop
        $0 start
        ;;

    status)
        status $DAEMON_PATH
        ;;

    *)
        echo "usage: $0 {start|stop|restart|force-reload|status}"
        exit 1
esac

exit 0
