#! /bin/sh -e

# bin/couchdb.tpl.  Generated from couchdb.tpl.in by configure.

# Copyright (C) 2007 Noah Slater <nslater@bytesexual.org>.

# This file is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.

# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.

# You should have received a copy of the GNU General Public License along with
# this file; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

SCRIPT_OK=0
SCRIPT_ERROR=1

INTERACTIVE_PREDICATE=false
BACKGROUND_PREDICATE=false
SHUTDOWN_PREDICATE=false

LIB_DIRECTORY=/var/lib/couchdb
LOG_DIRECTORY=/var/lib/log/couchdb

INI_FILE=/etc/couchdb/couch.ini
PID_FILE=/var/lib/run/couchdb.pid
STDOUT_FILE=couchdb.stdout
STDERR_FILE=couchdb.stderr

display_version () {
    # Display version and copyright information.

    cat << EOF
couchdb - CouchDB 0.7.2

Copyright (C) 2007 Damien Katz <damien_katz@yahoo.com>.

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA 02110-1301, USA.

Written by Damien Katz <damien_katz@yahoo.com>.
EOF
}

display_help () {
    # Display a short description of the script's behaviour.

    basename=$1
    cat << EOF
Usage: $basename [OPTION]

The $basename command runs the CouchDB server.

The exit status is 0 for success or 1 for failure.

Options:

  -h       display a short help message and exit
  -V       display version information and exit
  -c FILE  set the configuration FILE (defaults to $INI_FILE)
  -i       use the interactive Erlang shell
  -b       spawn as a background process (trumps the \`-s' option)
  -n       remove existing process ID file
  -p FILE  set the background process ID FILE (defaults to $PID_FILE)
  -o FILE  redirect background stdout to FILE (defaults to $STDOUT_FILE)
  -e FILE  redirect background stderr to FILE (defaults to $STDERR_FILE)
  -s       display the status of the background process
  -d       shutdown the background process

Report bugs via the web at <http://groups.google.com/group/couchdb>.

Report bugs via email to <couchdb@googlegroups.com>.
EOF
}

display_error () {
    # Display a short instruction referring users to further documentation.

    basename=$1
    echo "Try \`"$basename" -h' for more information."
}

_load_configuration () {
    # Load ini configuration and overwrite default variables.

    dbrootdir_ini_value=$(awk -F = "/^DbRootDir=/{print \$2}" < $INI_FILE)
    if test -n "$dbrootdir_ini_value"; then
        LIB_DIRECTORY=$dbrootdir_ini_value
    fi
    logfile_ini_value=$(awk -F = "/^LogFile=/{print \$2}" < $INI_FILE)
    if test -n "$logfile_ini_value"; then
        LOG_DIRECTORY=$(dirname $logfile_ini_value)
    fi
}

_get_pid () {
    if test -f $PID_FILE; then
        PID=$(cat $PID_FILE)
    fi
    if test -z "$PID"; then
        # Resort to searching for the running process manually.
        PID=$(ps auxww | grep -- "-boot /usr/lib/erlang/bin/couch" | \
            grep -v grep | awk "{print \$2}")
    fi
    echo $PID
}

check_status () {
    # Check the status of the running CouchDB process.

    expected_status=$1
    PID=$(_get_pid)
    if test -n "$PID"; then
        if $(ps $PID > /dev/null); then
            echo "CouchDB is running as process $PID. Time to relax."
        else
            echo "CouchDB is not running and a stale PID file exists: $PID_FILE"
            return $SCRIPT_ERROR
        fi
        if test "$expected_status" = "not-running"; then
            return $SCRIPT_ERROR
        fi
    else
        if test ! "$expected_status" = "not-running"; then
            echo "CouchDB is not running."
        fi
    fi
    return $SCRIPT_OK
}

check_environment () {
    # Check the environment for common problems to prevent nasty backtraces.

    message_prefix="CouchDB needs write permission on the"
    if test ! -w $LIB_DIRECTORY; then
        echo "$message_prefix data directory: $LIB_DIRECTORY"
        exit $SCRIPT_ERROR
    fi
    if test ! -w $LOG_DIRECTORY; then
        echo "$message_prefix log directory: $LOG_DIRECTORY"
        exit $SCRIPT_ERROR
    fi
    message_prefix="CouchDB needs write permission on data file"
    for file in `find $LIB_DIRECTORY -type f`; do
        if test ! -w $file; then
            echo "$message_prefix: $file"
            exit $SCRIPT_ERROR
        fi
    done
    message_prefix="CouchDB needs write permission on log file"
    for file in `find $LOG_DIRECTORY -type f`; do
        if test ! -w $file; then
            echo "$message_prefix: $file"
            exit $SCRIPT_ERROR
        fi
    done
    if test "$BACKGROUND_PREDICATE" = "true"; then
        touch $PID_FILE 2> /dev/null || true
        touch $STDOUT_FILE 2> /dev/null || true
        touch $STDERR_FILE 2> /dev/null || true
        message_prefix="CouchDB needs write permission on the"
        if test ! -w $PID_FILE; then
            echo "$message_prefix PID file: $PID_FILE"
            exit $SCRIPT_ERROR
        fi
        if test ! -w $STDOUT_FILE; then
            echo "$message_prefix STDOUT file: $STDOUT_FILE"
            exit $SCRIPT_ERROR
        fi
        if test ! -w $STDERR_FILE; then
            echo "$message_prefix STDERR file: $STDERR_FILE"
            exit $SCRIPT_ERROR
        fi
        message_prefix="CouchDB needs a regular"
        if ! echo 2> /dev/null >> $PID_FILE; then
            echo "$message_prefix PID file: $PID_FILE"
            exit $SCRIPT_ERROR
        fi
        if ! echo 2> /dev/null >> $STDOUT_FILE; then
            echo "$message_prefix STDOUT file: $STDOUT_FILE"
            exit $SCRIPT_ERROR
        fi
        if ! echo 2> /dev/null >> $STDERR_FILE; then
            echo "$message_prefix STDERR file: $STDERR_FILE"
            exit $SCRIPT_ERROR
        fi
    fi
}

start_couchdb () {
    # Start CouchDB with the Erlang interpreter.

    check_status not-running
    check_environment
    interactive_option="+Bd -noinput"
    if test "$INTERACTIVE_PREDICATE" = "true"; then
        interactive_option=""
    fi
    if test "$BACKGROUND_PREDICATE" = "true"; then
        touch $PID_FILE
        interactive_option="+Bd -noinput"
    fi
    command="/usr/bin/erl $interactive_option -sasl errlog_type error \
        -pa /usr/lib/erlang/lib/couch-0.7.2/ebin \
            /usr/lib/erlang/lib/couch_inets-4.7.5/ebin \
        -boot /usr/lib/erlang/bin/couch \
        -couchini $INI_FILE"
    if test "$BACKGROUND_PREDICATE" = "true"; then
        # XXX: This should use the `' option but we are unable to get
        # XXX: the PID using this method without special provisions.
        $command -detached -pidfile $PID_FILE > $STDOUT_FILE 2> $STDERR_FILE
        PID=$(_get_pid)
        echo "CouchDB has started as process $PID. Time to relax."
    else
        exec $command
    fi
}

stop_couchdb () {
    # Send SIGHUP to the running CouchDB process.

    PID=$(_get_pid)
    if test -n "$PID"; then
        if kill -1 $PID 2> /dev/null; then
            echo > $PID_FILE
            echo "CouchDB has been shutdown."
            return $SCRIPT_OK
        else
            echo "Could not shutdown CouchDB. Check the PID file: $PID_FILE"
            return $SCRIPT_ERROR
        fi
    else
        echo "CouchDB is not running."
    fi
}

parse_script_option_list () {
    # Parse the script option list and take the appropriate action.

    basename=$(basename $0)
    if ! argument_list=$(getopt hVc:ibp:o:e:nsd $@); then
        echo
        display_error $basename
        exit $SCRIPT_ERROR
    fi
    eval set -- "$argument_list"
    while [ $# -gt 0 ]; do
        case "$1" in
            -h)
                shift
                display_help $basename
                exit $SCRIPT_OK
                ;;
            -V)
                shift
                display_version
                exit $SCRIPT_OK
                ;;
            -c)
                shift
                INI_FILE=$1
                shift
                ;;
            -i)
                shift
                INTERACTIVE_PREDICATE=true
                ;;
            -b)
                shift
                BACKGROUND_PREDICATE=true
                ;;
            -n)
                shift
                rm -f $PID_FILE
                ;;
            -p)
                if test "$BACKGROUND_PREDICATE" != "true" \
                    -a "$SHUTDOWN_PREDICATE" != "true"; then
                    cat << EOF
You must use the \`-p' option with the \`-b' or \`-d' option.
EOF
                    echo
                    display_error $basename
                    exit $SCRIPT_ERROR
                fi
                shift
                PID_FILE=$1
                shift
                ;;
            -o)
                if test ! "$BACKGROUND_PREDICATE" = "true"; then
                    cat << EOF
You must use the \`-o' option with the \`-b' option.
EOF
                    echo
                    display_error $basename
                    exit $SCRIPT_ERROR
                fi
                shift
                STDOUT_FILE=$1
                shift
                ;;
            -e)
                if test ! "$BACKGROUND_PREDICATE" = "true"; then
                    cat << EOF
You must use the \`-e' option with the \`-b' option.
EOF
                    echo
                    display_error $basename
                    exit $SCRIPT_ERROR
                fi
                shift
                STDERR_FILE=$1
                shift
                ;;
            -s)
                shift
                check_status
                exit $SCRIPT_OK
                ;;
            -d)
                shift
                SHUTDOWN_PREDICATE=true
                ;;
            --)
                shift
                break
                ;;
            *)
                break
                ;;
        esac
    done
    _load_configuration
    if test "$SHUTDOWN_PREDICATE" = "true"; then
        stop_couchdb
    else
        start_couchdb
    fi
}

parse_script_option_list $@
