#!/bin/sh
#
# Startup / shutdown script for the couchbase server
#
# Copyright (c) 2011, Couchbase, Inc.
# All rights reserved
#
#
### BEGIN INIT INFO
# Provides:          couchbase-server-community
# Required-Start:    $network $local_fs
# Required-Stop:
# Should-Start:      $named
# Should-Stop:
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    couchbase server
# Description:          couchbase server

### END INIT INFO

. /etc/init.d/functions

if [ "$(id -u)" != "0" ]; then
    echo "Must run as root"
    exit 1
fi

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

DAEMON=/opt/couchbase/bin/couchbase-server
PIDFILE=/opt/couchbase/var/lib/couchbase/couchbase-server.pid
NODEFILE=/opt/couchbase/var/lib/couchbase/couchbase-server.node
COOKIEFILE=/opt/couchbase/var/lib/couchbase/couchbase-server.cookie

test -f $DAEMON || exit 0

# Otherwise, RHEL (and apparently Fedora) tries to "help" and set soft
# limit of core file size to 0 for daemons. It's done as part of
# daemon shell function shortly after changing user. See MB-6601
DAEMON_COREFILE_LIMIT=unlimited

start() {
    touch $PIDFILE $NODEFILE $COOKIEFILE
    chown couchbase $PIDFILE $NODEFILE $COOKIEFILE
    cd /opt/couchbase/var/lib/couchbase
    ulimit -n 40960
    ulimit -c unlimited
    ulimit -l unlimited
    daemon --user couchbase "$DAEMON" -- -noinput -detached | tee /opt/couchbase/var/lib/couchbase/logs/start.log 2>&1
    errcode=$?
    return $errcode
}

stop() {
    daemon "$DAEMON" -k
    errcode=$?
    return $errcode
}

running() {
    pidofproc -p $PIDFILE $DAEMON >/dev/null
    errcode=$?
    return $errcode
}

case $1 in
    start)
        if running ; then
            warning && echo "couchbase-server-community is already started"
            exit 0
        fi
        echo -n $'Starting couchbase-server-community\n'
        start
        echo
        ;;
    stop)
        echo -n $'Stopping couchbase-server-community\n'
        stop
        echo
        ;;
    restart)
        echo -n $'Stopping couchbase-server-community\n'
        stop
        echo
        echo -n $'Starting couchbase-server-community\n'
        start
        echo
        ;;
    status)
        if running ; then
            echo -n $'couchbase-server-community is running\n'
            exit 0
        else
            echo -n $'couchbase-server-community is not running\n'
            exit 3
        fi
        ;;
    *)
        echo "Usage: /etc/init.d/couchbase-server {start|stop|restart|status}" >&2
        exit 3
esac
