#!/bin/sh
#
# Simple server init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.

### BEGIN INIT INFO
# Provides:     kv_6379
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    KV data structure server
# Description:          KV data structure server. See https://kv.io
### END INIT INFO

KVPORT=6379
EXEC=/usr/local/bin/kv-server
CLIEXEC=/usr/local/bin/kv-cli

PIDFILE=/var/run/kv_${KVPORT}.pid
CONF="/etc/kv/${KVPORT}.conf"

case "$1" in
    start)
        if [ -f $PIDFILE ]
        then
                echo "$PIDFILE exists, process is already running or crashed"
        else
                echo "Starting KV server..."
                $EXEC $CONF
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
                echo "$PIDFILE does not exist, process is not running"
        else
                PID=$(cat $PIDFILE)
                echo "Stopping ..."
                $CLIEXEC -p $KVPORT shutdown
                while [ -x /proc/${PID} ]
                do
                    echo "Waiting for KV to shutdown ..."
                    sleep 1
                done
                echo "KV stopped"
        fi
        ;;
    *)
        echo "Please use start or stop as first argument"
        ;;
esac
