#!/bin/sh

# Author: Foundation for Learning Equality
#
# /etc/init.d/kolibri

### BEGIN INIT INFO
# Provides:          kolibri
# Required-Start:    $local_fs $remote_fs $network $syslog $named
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: kolibri daemon, an offline education platform
### END INIT INFO

set -e

if !(whoami | grep "root" -q)
then
	echo "You need to be root"
	exit 1
fi

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

. /lib/lsb/init-functions

# Prefer runuser over su
# See: https://github.com/learningequality/kolibri-installer-debian/issues/90
# Check if runuser exists - it doesn't on 14.04
if which runuser > /dev/null
then
  SU_COMMAND="runuser"
else
  SU_COMMAND="su"
fi


set -o allexport
. /etc/default/kolibri
set +o allexport

# We wanted this pattern, but it doesn't work on Ubuntu 14.04
# because $HOME is unavailable when preserving the env with -p.
#   su $KOLIBRI_USER -l -p -s /bin/sh -c "COMMAND"
# However, this seems to preserve environment and switch $HOME
# by default on both 14.04 and 16.04:
#   su kolibri -c "COMMAND"

# Safeguard $KOLIBRI_USER, because if it is somehow unset, we will
# be running kolibri as root user.
if test "$KOLIBRI_USER" = ""
then
  echo "KOLIBRI_USER not defined"
  exit 1
fi

case "$1" in
  start)
    # run kolibri as another user, the one who generated this file
    $SU_COMMAND $KOLIBRI_USER -c "$KOLIBRI_COMMAND start"
    ;;
  stop)
    $SU_COMMAND $KOLIBRI_USER -c "$KOLIBRI_COMMAND stop"
    ;;
  restart)
    $SU_COMMAND $KOLIBRI_USER -c "$KOLIBRI_COMMAND stop"
    $SU_COMMAND $KOLIBRI_USER -c "$KOLIBRI_COMMAND start"
    ;;
  status)
    $SU_COMMAND $KOLIBRI_USER -c "$KOLIBRI_COMMAND status"
    ;;
  *)
    log_success_msg "Usage: /etc/init.d/kolibri {start|stop|restart|status}"
    exit 1
esac

