#!/bin/bash
# /etc/init.d/jmuconfig: start and stop the JMUConfig service

NAME="jmuconfig"
DAEMON="/usr/bin/node"

DAEMONARGS_MIN="--gc_global --always_compact"
DAEMONARGS="${DAEMONARGS_MIN} server.js"
DAEMONOOMSCORE="900"
PIDFILE="/var/run/${NAME}.pid"
READYFILE="/tmp/${NAME}.ready"
CHDIR="/usr/lib/${NAME}"
CONFDIR="/etc/${NAME}"

TZGEN="/usr/bin/jmuconfig-gen-timezones.sh"
TZJS="/var/lib/jmuconfig/www/js/timezones.js"

VNCCONFDIR="/etc/x11vnc"

if `start-stop-daemon 2>&1 | grep BusyBox >/dev/null`; then
  STARTSTOP_BUSYBOX=1
fi

[ -e /etc/default/jmuconfig ] && . /etc/default/jmuconfig

init() {
    init_tz
    init_vnc
    init_perms
}

init_perms() {
    chgrp -R admin "${CONFDIR}"
    chmod 2775 "${CONFDIR}"  # setgid + rwx for group
}

# Increase OOM score so this daemon is more likely to be killed
set_oomscore() {
    {
        i=0
        while [ ${i} -lt 10 ] && [ ! -e "${PIDFILE}" ]; do
            echo "waiting on ${PIDFILE}"
            sleep 1
            i=`expr ${i} + 1`
        done
        if [ -e "${PIDFILE}" ]; then
            PID=$(cat "${PIDFILE}")
            echo ${DAEMONOOMSCORE} > /proc/$PID/oom_score_adj
        else
            echo "giving up"
        fi
    } &
}

init_tz() {
    mkdir -p `dirname ${TZJS}`
    "${TZGEN}" > "${TZJS}"
}

init_vnc() {
    mkdir -p "${VNCCONFDIR}"
    chgrp -R admin "${VNCCONFDIR}"
    chmod 2775 "${VNCCONFDIR}"  # setgid + rwx for group
}

do_start()
{
    if [ -e ${PIDFILE} ]; then
        echo "Already running (${PIDFILE})"
        return
    fi

    echo "Starting ${NAME}"
    init

    # BusyBox does not have --chdir
    if [ "${STARTSTOP_BUSYBOX}" = "1" ]; then
        cd "${CHDIR}"
    else
        STARTSTOPARGS="--chdir ${CHDIR}"
    fi

    start-stop-daemon --start \
        --background \
        --chuid admin \
        --pidfile "${PIDFILE}" \
        --make-pidfile ${STARTSTOPARGS} \
        --exec /bin/bash \
        -- -c "exec /etc/init.d/node.sh ${JMUCONFIG_OPTS} ${DAEMONARGS}"
        #-- -c "exec ${DAEMON} ${JMUCONFIG_OPTS} ${DAEMONARGS} 2>&1 | /usr/bin/logger -t JMUConfig"
    [ $? -eq 0 ] || exit 1

    set_oomscore

    echo "."
}

do_stop()
{
    echo -n "Stopping ${NAME}"

    # kill dbus children (which are parented to init)
    pkill -f '^dbus-daemon .*dbus-jmuconfig.*'
    # and nodejs
    [ -e "${PIDFILE}" ] && pkill -P $(cat "${PIDFILE}")

    start-stop-daemon --stop --retry=TERM/10/KILL/5 --oknodo --pidfile "${PIDFILE}"
    [ $? -eq 0 ] || exit 1

    rm -f "${PIDFILE}"
    rm -f "${READYFILE}"
    echo "."
}

case "$1" in

  start)
    do_start
    ;;

  stop)
    do_stop
    ;;

  restart)

    do_stop
    sleep 2
    do_start

    echo "."
    ;;

  *)
    echo "Usage: /etc/init.d/jmuconfig {start|stop|restart}"
    exit 1
esac

exit 0
