#!/bin/sh
#
# Moonraker Service
#

USER_DATA=/usr/data
PROG=$USER_DATA/moonraker/moonraker-env/bin/python
PY_SCRIPT=$USER_DATA/moonraker/moonraker/moonraker/moonraker.py
MOONRAKER_TMP_DIR=$USER_DATA/moonraker/tmp
PRINTER_DATA_DIR=$USER_DATA/printer_data
PRINTER_CONFIG_DIR=$PRINTER_DATA_DIR/config
PRINTER_LOGS_DIR=$PRINTER_DATA_DIR/logs
PID_FILE=/var/run/moonraker.pid

start() {
        [ -d $PRINTER_DATA_DIR ] || mkdir -p $PRINTER_DATA_DIR
        [ -d $PRINTER_CONFIG_DIR ] || mkdir -p $PRINTER_CONFIG_DIR
        [ -d $PRINTER_LOGS_DIR ] || mkdir -p $PRINTER_LOGS_DIR
        rm -rf $MOONRAKER_TMP_DIR && mkdir -p $MOONRAKER_TMP_DIR
        export TMPDIR=$MOONRAKER_TMP_DIR
        HOME=/root start-stop-daemon -S -q -b -m -p $PID_FILE \
          --exec $PROG -- $PY_SCRIPT -d $PRINTER_DATA_DIR
}
stop() {
        start-stop-daemon -K -q -p $PID_FILE
}
restart() {
        stop
        sleep 1
        start
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart|reload)
        restart
        ;;
  *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?
