#!/bin/sh -e

# chkconfig: 345 91 10
# description: distributed document database server
# processname: couchdb
# config: /etc/default/couchdb
# pidfile: /var/run/couchdb.pid


# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

. /etc/init.d/functions

CONFIGFILE=/etc/sysconfig/couchdb
COUCHDB=/usr/sbin/couchdb

SourceIfExists "$CONFIGFILE"

RETVAL=0

start()
{
	local command sd_params
	command="$COUCHDB -b"
	sd_params=""
	test -n "$COUCHDB_INI_FILE" && command="$command -a $COUCHDB_INI_FILE" || :
	test -n "$COUCHDB_PID_FILE" && command="$command -p $COUCHDB_PID_FILE" || :
	test -n "$COUCHDB_STDOUT_FILE" && command="$command -o $COUCHDB_STDOUT_FILE" || :
	test -n "$COUCHDB_STDERR_FILE" && command="$command -e $COUCHDB_STDERR_FILE" || :
	if test -n "$COUCHDB_USER"; then
		if test -n "$COUCHDB_PID_FILE"; then
			touch "$COUCHDB_PID_FILE"
			chown "$COUCHDB_USER" "$COUCHDB_PID_FILE"
		fi
		sd_params="--user $COUCHDB_USER"
	fi
	start_daemon $sd_params -- $command
	RETVAL=$?
	return $RETVAL
}

stop()
{
	local command
	#if checkstatus >/dev/null 2>&1; then
	#	:
	#else
	#	msg_not_running couchdb; echo_passed || echo
	#	RETVAL=0
	#	return 0
	#fi
	command="$COUCHDB -d"
	test -n "$COUCHDB_PID_FILE" && command="$command -p $COUCHDB_PID_FILE" || :
	msg_stopping couchdb
	if test -n "$COUCHDB_USER"; then
		su -l "$COUCHDB_USER" -s /bin/sh -c "$command" >/dev/null
		RETVAL=$?
		test "$RETVAL" = 0 && success "couchdb stop" || failure "couchdb stop"
		echo
		return $RETVAL
	else
		$command
		RETVAL=$?
		test "$RETVAL" = 0 && success "couchdb stop" || failure "couchdb stop"
		echo
		return $RETVAL
	fi
	test -n "$COUCHDB_PID_FILE" && rm -f "$COUCHDB_PID_FILE" ||:
}

restart()
{
	stop
	sleep 2
	start
}

checkstatus()
{
	local command
	command="$COUCHDB -s"
	if test -n "$COUCHDB_USER"; then
		su -l "$COUCHDB_USER" -s /bin/sh -c "$command" 2>&1 | grep -q relax
		RETVAL=$?
		return $RETVAL
	else
		$command 2>&1 | grep -q relax
		RETVAL=$?
		return $RETVAL
	fi
}

# See how we were called.
case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        reload|restart)
                restart
                ;;
        condstop)
                if checkstatus >/dev/null 2>&1; then
                        stop
		else
			msg_not_running couchdb; echo_passed || echo
                fi
                ;;
        condrestart)
                if checkstatus >/dev/null 2>&1; then
                        restart
		else
			msg_not_running couchdb; echo_passed || echo
                fi
                ;;
        condreload)
                if checkstatus >/dev/null 2>&1; then
                        restart
		else
			msg_not_running couchdb; echo_passed || echo
                fi
                ;;
        status)
		checkstatus
               ;;
        *)
                msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
                RETVAL=1
esac

exit $RETVAL
