#!/bin/sh

# PROVIDE: couchdb3
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# couchdb3_enable (bool):       Set to NO by default.
#                               Set it to YES to enable couchdb.

. /etc/rc.subr

name=couchdb3
rcvar=couchdb3_enable

start_cmd="${name}_start"
stop_cmd="${name}_stop"
status_cmd="${name}_status"

load_rc_config $name

: ${couchdb3_enable:="NO"}
: ${couchdb3_user="couchdb"}
: ${couchdb3_erl_flags="-couch_ini /usr/local/libexec/couchdb3/etc/default.ini /usr/local/etc/couchdb3/local.ini"}
: ${couchdb3_chdir="/var/db/couchdb3"}

command="/usr/local/lib/erlang25/bin/erl"
pidfile="/var/run/${name}.pid"
daemonpidfile="/var/run/${name}-daemon.pid"

erl_sasl='-sasl releases_dir \"couchdb3/releases\"'
erl_boot='-boot /usr/local/libexec/couchdb3/releases/3.3.3/couchdb -boot_var RELTOOL_EXT_LIB /usr/local/libexec/couchdb3/lib'
erl_args='-args_file /usr/local/etc/couchdb3/vm.args'
erl_flags="${erl_sasl} ${erl_boot} ${erl_args} ${couchdb3_erl_flags}"

couchdb3_start()
{
    # chdir manually as overriding _start() blocks rc.subr defaults
    cd "${couchdb3_chdir}"
    /usr/sbin/daemon -p ${pidfile} \
        -P ${daemonpidfile} \
        -t ${name} \
        -u ${couchdb3_user} \
        env ERL_FLAGS="${erl_flags}" \
        HOME=/var/run/couchdb3 \
        ERL_CRASH_DUMP=/var/run/couchdb3/erl_crash.dump \
        COUCHDB_FAUXTON_DOCROOT=/usr/local/www/couchdb3 \
        COUCHDB_QUERY_SERVER_JAVASCRIPT="/usr/local/libexec/couchdb3/bin/couchjs /usr/local/libexec/couchdb3/share/server/main.js" \
        COUCHDB_QUERY_SERVER_COFFEESCRIPT="/usr/local/libexec/couchdb3/bin/couchjs /usr/local/libexec/couchdb3/share/server/main-coffee.js" \
        ${command}
}

couchdb3_stop()
{
    echo -n "Stopping ${name}: "
    retval=0
    if ! status_quiet
    then
        echo "already stopped"
        return 1
    else
        couchdb3_pids=$(/bin/pgrep -ifU ${couchdb3_user} ${name})
        kill ${couchdb3_pids}
        wait_for_pids ${couchdb3_pids}
        retval=$?
        echo "stopped"
    fi
    return $retval
}

couchdb3_status()
{
    /bin/pgrep -ifU ${couchdb3_user} ${name}  > /dev/null && status="$?" || status="$?"
    if [ "${status}" = 0 ]; then
        echo "${name} is running"
        return 0
    elif [ "${status}" = 4 ]; then
        echo "could not access PID file for ${name}"
        return ${status}
    else
        echo "${name} is not running"
        return ${status}
    fi
}

status_quiet()
{
    couchdb3_status >/dev/null 2>&1
}

run_rc_command $1

