#!/bin/sh

SUPERVISORD="/usr/bin/supervisord_orig"
PIDFILE="/var/log/supervisord.pid"

# chkconfig: 345 15 15

start() {
    #Run noobaa_init script before start
    local path="/root/node_modules/noobaa-core/src/deploy/NVA_build/"
    if [ "${container}" == "docker" ]
    then
        path="/noobaa_init_files/"
    fi
    ${path}/noobaa_init.sh
    #Abort pod start if noobaa_init fails
    rc=$?
    if [ ${rc} -ne 0 ]; then
        echo "noobaa_init failed with exit code ${rc}. aborting"
        exit ${rc}
    fi

    if [ ! -x "$SUPERVISORD" ]; then
        echo "$SUPERVISORD is not executable."
        logger -p local0.info -t Superd "$SUPERVISORD is not executable."
        exit 1
    fi
    echo "Starting ..."
    logger -p local0.info -t Superd "Starting ..."
    ulimit -n 102400; $SUPERVISORD --pidfile $PIDFILE -n

    return $?
}

stop() {
    echo "Stopping ..."
    logger -p local0.info -t Superd "Stopping ..."
    local supervisord_orig_pid=$(pgrep -lf $SUPERVISORD | awk '{print $1}')
    echo "supervisord_orig_pid=$supervisord_orig_pid"
    logger -p local0.info -t Superd "supervisord_orig_pid=$supervisord_orig_pid"
    kill -9 ${supervisord_orig_pid}

    local web_server_pid=$(pgrep -lf web_server.js | awk '{print $1}')
    echo "web_server_pid=$web_server_pid"
    logger -p local0.info -t Superd "web_server_pid=$web_server_pid"
    kill -9 ${web_server_pid}

    local bg_workers_pid=$(pgrep -lf bg_workers.js | awk '{print $1}')
    echo "bg_workers_pid=$bg_workers_pid"
    logger -p local0.info -t Superd "bg_workers_pid=$bg_workers_pid"
    kill -9 ${bg_workers_pid}

    local hosted_agents_starter_pid=$(pgrep -lf hosted_agents_starter.js | awk '{print $1}')
    echo "hosted_agents_starter_pid=$hosted_agents_starter_pid"
    logger -p local0.info -t Superd "hosted_agents_starter_pid=$hosted_agents_starter_pid"
    kill -9 ${hosted_agents_starter_pid}

    local s3rver_starter_pids=$(pgrep -lf s3rver_starter.js | awk '{print $1}')
    echo "s3rver_starter_pids=$s3rver_starter_pids"
    logger -p local0.info -t Superd "s3rver_starter_pids=$s3rver_starter_pids"
    kill -9 ${s3rver_starter_pids}

    local mongo_pids=$(pgrep -lf mongo | awk '{print $1}')
    echo "mongo_pids=$mongo_pids"
    logger -p local0.info -t Superd "mongo_pids=$mongo_pids"
    kill -2 ${mongo_pids}

    local p=$(cat $PIDFILE)
    kill -9 ${p}
    [ $? -eq 0 ] && rm -f $PIDFILE
    return
}

case $1 in
    start)      start;;
    stop)       stop;;
    restart)    stop
                sleep 1
                start;;
    *)          echo "$0 start|stop|restart"
                exit 2;;
esac
