#! /usr/bin/env bash
#
# Copyright (c) 2010-2020, Couchbase, Inc.
# All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

SOFTWARE_VERSION="6.6.0-7909"
if [ x"${SOFTWARE_VERSION}" = "x" ]
then
   SOFTWARE_VERSION="unsupported developer build"
fi

ENTERPRISE=`echo FALSE | tr '[:upper:]' '[:lower:]'`

if [ x"${ENTERPRISE}" = "xtrue" ]
then
   SOFTWARE_VERSION="${SOFTWARE_VERSION} (EE)"
else
   SOFTWARE_VERSION="${SOFTWARE_VERSION} (CE)"
fi

PATH="/opt/couchbase/bin":$PATH
export PATH

ERL_LIBS="/opt/couchbase/lib/ns_server/erlang/lib:/opt/couchbase/lib/couchdb/erlang/lib:/opt/couchbase/lib/couchdb/plugins"
export ERL_LIBS

NS_EBIN_PATH="/opt/couchbase/lib/ns_server/erlang/lib/ns_server/ebin"

DEFAULT_CONFIG_DIR="/opt/couchbase/etc/couchdb/default.d"
DEFAULT_CONFIG_FILE="/opt/couchbase/etc/couchdb/default.ini"
LOCAL_CONFIG_DIR="/opt/couchbase/etc/couchdb/local.d"
LOCAL_CONFIG_FILE="/opt/couchbase/etc/couchdb/local.ini"

PIDFILE="/opt/couchbase/var/lib/couchbase/couchbase-server.pid"
COOKIEFILE="/opt/couchbase/var/lib/couchbase/couchbase-server.babysitter.cookie"
NODEFILE="/opt/couchbase/var/lib/couchbase/couchbase-server.babysitter.node"
STATIC_CONFIG_PATH="/opt/couchbase/etc/couchbase/static_config"
CB_DATA_DIR="/opt/couchbase/var/lib/couchbase"
SSL_DIST_OPTFILE="/opt/couchbase/etc/couchbase/ssl_dist_opts"
CB_DIST_CFG_FILE="$CB_DATA_DIR/config/dist_cfg"
HOSTS_CFG_FILE="/opt/couchbase/etc/couchbase/hosts.cfg"

couch_start_arguments=""

LD_LIBRARY_PATH="/opt/couchbase/lib":"/opt/couchbase/lib/memcached":$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

ERL_CRASH_DUMP_BASE=erl_crash.dump.$(date +%s).$$
ERL_CRASH_DUMP=$ERL_CRASH_DUMP_BASE.babysitter
export ERL_CRASH_DUMP_BASE
export ERL_CRASH_DUMP

ERL_FULLSWEEP_AFTER=512
export ERL_FULLSWEEP_AFTER

# For some obscure reason erl requires HOME environment variable to be set.
if [ -z "$HOME" ]
then
    export HOME=/tmp
fi

_check_ulimit() {
    lim=`ulimit $1`
    if [ $lim != "unlimited" ] && [ $lim -lt $2 ]
    then
        cat <<EOF

The $3 for the couchbase user is set too low ($lim).
It must be at least $2.

EOF

        if [ -f /etc/security/limits.conf ]
        then
            cat <<EOF
Normally this can be increased by adding the following lines to
/etc/security/limits.conf:

couchbase              soft    $4                  <value>
couchbase              hard    $4                  <value>

Where <value> is greater than $2. The procedure may be totally
different if you're running so called "non-root/non-sudo install" or
if you've built Couchbase Server from source.

EOF
        fi
    fi
}

_prepare_datadir () {
    test -d "$CB_DATA_DIR" || mkdir -p "$CB_DATA_DIR"
    cd "$CB_DATA_DIR"
}

_maybe_start_epmd () {
    # Initialize distributed erlang on the system (i.e. epmd)
    erl -noshell -setcookie nocookie -sname init -run init stop 2>&1 > /dev/null
    if [ $? -ne 0 ]
    then
        exit 1
    fi
}

_add_config_file () {
    couch_start_arguments="$couch_start_arguments $1"
}

_add_config_dir () {
    for file in "$1"/*.ini; do
        if [ -r "$file" ]; then
          _add_config_file "$file"
        fi
    done
}

_load_config () {
    _add_config_file "$DEFAULT_CONFIG_FILE"
    _add_config_dir "$DEFAULT_CONFIG_DIR"
    _add_config_file "$LOCAL_CONFIG_FILE"
    _add_config_dir "$LOCAL_CONFIG_DIR"
    if [ "$COUCHDB_ADDITIONAL_CONFIG_FILE" != '' ]
    then
        _add_config_file "$COUCHDB_ADDITIONAL_CONFIG_FILE"
    fi
}

_drop_old_crashdumps () {
    KEEP="`ls -1 erl_crash.dump.* 2>/dev/null | sort | tail -n 10`"
    for file in erl_crash.dump.*; do
        if [[ "$KEEP" != *$file* ]]; then
            rm -f $file
        fi
    done
}


_start() {
    # Warn if user limits are restrictive.
    _check_ulimit -u 10000 "maximum number of processes" "nproc"
    _check_ulimit -n 70000 "maximum number of open files" "nofile"

    _prepare_datadir
    _maybe_start_epmd
    _load_config

    # note: we depend on pwd being $datadir from _prepare_datadir
    _drop_old_crashdumps

    umask 007

    exec erl \
        +A 16 \
        -smp enable \
        +sbwt none \
        -kernel error_logger false \
                inetrc "\"$HOSTS_CFG_FILE\"" \
                dist_config_file "\"$CB_DIST_CFG_FILE\"" \
        -sasl sasl_error_logger false \
        -hidden \
        -name 'babysitter_of_ns_1@cb.local' \
        -proto_dist cb \
        -epmd_module cb_epmd \
        -ssl_dist_optfile $SSL_DIST_OPTFILE \
        -setcookie nocookie \
        $* \
        -run ns_babysitter_bootstrap -- \
        -couch_ini $couch_start_arguments \
        -ns_babysitter cookiefile "\"$COOKIEFILE\"" \
        -ns_babysitter nodefile "\"$NODEFILE\"" \
        -ns_babysitter pidfile "\"$PIDFILE\"" \
        -ns_server config_path "\"$STATIC_CONFIG_PATH\""
}

_stop() {
    [ -f "$COOKIEFILE" -a -f "$NODEFILE" ] || return 1

    cookie=`cat "$COOKIEFILE"`
    node=`cat "$NODEFILE"`

    erl \
        -name 'executioner@cb.local' \
        -kernel dist_config_file "\"$CB_DIST_CFG_FILE\"" \
                inetrc "\"$HOSTS_CFG_FILE\"" \
        -proto_dist cb \
        -epmd_module cb_epmd \
        -ssl_dist_optfile $SSL_DIST_OPTFILE \
        -noshell \
        -hidden \
        -setcookie "$cookie" \
        -eval "ns_babysitter_bootstrap:remote_stop('$node')"

    errcode=$?

    if [ $errcode -eq 0 ]; then
        rm "$COOKIEFILE" "$NODEFILE"

        epmd -kill >/dev/null
    fi

    return $errcode
}

_status() {
    if [ ! -f "$PIDFILE" ]; then
        echo "Couchbase Server is not running"
        return 3
    fi

    pid=`cat "$PIDFILE"`

    progname=`ps -p "$pid" -c -o comm=`

    if [ "$progname" == "beam.smp" ]; then
        echo "Couchbase Server is running"
        return 0
    else
        echo "Couchbase Server is not running"
        return 1
    fi
}

usage() {
cat <<EOF
couchbase-server is a script to start/stop Couchbase Server.

Usage: $0 [--start|--status|--stop|--help|--version|-s|-k|-h|-v] [options]

  Recognized options:
     --start        Start Couchbase Server
     --status, -s   Determine if Couchbase Server is running
     --stop, -k     Stop Couchbase Server
     --help, -h     Print this help text
     --version, -v  Print software Version

If none of the recognized options are specifed, --start is implied.  In
this case, any trailing options and arguments will be passed to Couchbase
Server; they should NOT be used unless you know what you're doing.

EOF
}

_parse_options () {
    # the getopt lack support for longopts..
    if [ "$1" == "--version" ]
    then
      echo "Couchbase Server ${SOFTWARE_VERSION}"
      exit 0
    fi

    if [ "$1" == "--help" ]
    then
      usage
      exit 0
    fi

    if [ "$1" == "--status" ]
    then
      _status
      exit $?
    fi

    if [ "$1" == "--start" ]
    then
      _start -detached
      # No "exit" is required here because _start does an exec.
    fi

    if [ "$1" == "--stop" ]
    then
      _stop
      exit $?
    fi

    # set +e
    while getopts "kvhs" opt
    do
       case $opt in
       k)
         _stop
         exit $?
         ;;
       v)
         echo "Couchbase Server ${SOFTWARE_VERSION}"
         exit 0
         ;;
       h)
         usage
         exit 0
         ;;
       s)
         _status
         exit $?
         ;;
       *)
         break
         ;;
       esac
    done

    _start $*
}

_parse_options $*
