#!upstart
description "Secure and Encrypted Chat Server"
author      "Marc Wäckerlin (https://marc.wäckerlin.ch) <marc@waeckerlin.org>"

start on (local-filesystems and net-device-up)
stop on runlevel [!2345]

respawn

script
    echo $$ > /var/run/safechat.pid
    # there are some useful defaults
    # do not edit this file, overwrite values in /etc/default/safechat
    EXEC_SAFECHAT="/usr/bin/nodejs /usr/share/safechat/nodejs/safechat"
    SAFECHAT_LOG="/var/log/safechat.log"
    SAFECHAT_USER="safechat"
    SAFECHAT_PORT=""
    [ -r /etc/default/safechat ] && . /etc/default/safechat
    if test -n "${SAFECHAT_USER}"; then
        exec sudo -u "${SAFECHAT_USER}" ${EXEC_SAFECHAT} ${SAFECHAT_PORT} >> ${SAFECHAT_LOG} 2>&1
    else
        exec ${EXEC_SAFECHAT} ${SAFECHAT_PORT} >> ${SAFECHAT_LOG} 2>&1
    fi
end script

pre-start script
    SAFECHAT_LOG="/var/log/safechat.log"
    [ -r /etc/default/safechat ] && . /etc/default/safechat
    # Date format same as (new Date()).toISOString() for consistency
    echo "[2016-11-25T11:53:52.543Z] (sys) Starting" >> ${SAFECHAT_LOG}
end script

pre-stop script
    SAFECHAT_LOG="/var/log/safechat.log"
    [ -r /etc/default/safechat ] && . /etc/default/safechat
    rm /var/run/safechat.pid
    echo "[2016-11-25T11:53:52.544Z] (sys) Stopping" >> ${SAFECHAT_LOG}
end script
