#!@l_prefix@/bin/openpkg rc
##
##  rc.pm2 -- Run-Commands
##

%config
    pm2_enable="$openpkg_rc_def"
    pm2_node_flags="--harmony"
    pm2_modify_require="false"
    pm2_graceful_timeout="4000"
    pm2_bind_addr="127.0.0.1"
    pm2_bind_port_api="9615"
    pm2_bind_port_rpc="6666"
    pm2_bind_port_pub="6667"
    pm2_log_prolog="true"
    pm2_log_epilog="true"
    pm2_log_numfiles="10"
    pm2_log_minsize="1M"
    pm2_log_complevel="9"

%common
    pm2_vardir="@l_prefix@/var/pm2/run"
    pm2_pidfile="@l_prefix@/var/pm2/run/.pm2/pm2.pid"
    pm2_logfile="@l_prefix@/var/pm2/run/.pm2/pm2.log"
    pm2_signal () {
        [ -f $pm2_pidfile ] && kill -$1 `cat $pm2_pidfile`
    }
    pm2_exec () {
        (
            export HOME="$pm2_vardir"
            export PM2_NODE_OPTIONS="$pm2_node_flags"
            export PM2_MODIFY_REQUIRE="$pm2_modify_require"
            export PM2_GRACEFUL_TIMEOUT="$pm2_graceful_timeout"
            export PM2_BIND_ADDR="$pm2_bind_addr"
            export PM2_API_PORT="$pm2_bind_port_api"
            export PM2_RPC_PORT="$pm2_bind_port_rpc"
            export PM2_PUB_PORT="$pm2_bind_port_pub"
            exec @l_prefix@/sbin/pm2 ${1+"$@"}
        )
    }

%status -u @l_nusr@ -o
    pm2_usable="unknown"
    pm2_active="no"
    rcService pm2 enable yes && \
        pm2_signal 0 && pm2_active="yes"
    echo "pm2_enable=\"$pm2_enable\""
    echo "pm2_usable=\"$pm2_usable\""
    echo "pm2_active=\"$pm2_active\""

%start -u @l_nusr@
    rcService pm2 enable yes || exit 0
    rcService pm2 active yes && exit 0
    pm2_exec -s resurrect

%stop -u @l_nusr@
    rcService pm2 enable yes || exit 0
    rcService pm2 active no  && exit 0
    pm2_exec -s dump
    pm2_exec -s delete all
    pm2_exec -s kill
    sleep 2
    rm -f $pm2_pidfile >/dev/null 2>&1 || true

%restart -u @l_nusr@
    rcService pm2 enable yes || exit 0
    rcService pm2 active no  && exit 0
    rc pm2 stop start

%reload -u @l_nusr@
    rcService pm2 enable yes || exit 0
    rcService pm2 active no  && exit 0
    pm2_exec -s gracefulReload all

%daily -u @l_susr@
    rcService pm2 enable yes || exit 0
    shtool rotate -f \
        -n ${pm2_log_numfiles} -s ${pm2_log_minsize} -d \
        -z ${pm2_log_complevel} -m 664 -o @l_nusr@ -g @l_ngrp@ \
        -P "${pm2_log_prolog}" \
        -E "${pm2_log_epilog}; rc pm2 restart" \
        $pm2_logfile

