#!/bin/bash

MEMBASE_DIR='/home/teapot/membase/membase-server-community_1.6.0.1_src'
MEMBASE_CLI="$MEMBASE_DIR/membase-cli/membase"
NS_DIR="$MEMBASE_DIR/ns_server"
URI_BASE='http://localhost:8091'

# Handle command line arguments.

while getopts 'm:d:c:' flag; do
    case "$flag" in
        d) DATA_DIR="$OPTARG";;
        m) RAM_QUOTA="$OPTARG";;
        c) CONTINUE="$OPTARG";; # TODO: Redo this without a parameter
    esac
done

if [ -z "$DATA_DIR" -o -z "$RAM_QUOTA" ]; then
    exec >&2
    echo "Usage: $(basename "$0") -d DATA_DIR -m RAM_QUOTA"
    echo "Runs a clean membase instance and configures it with the given options."
    echo "Assumes that membase has been compiled and prepared."
    echo "If -c yes is given, an existing Membase database is \"continued\""
    echo "instead of a new one being created."
    exit 2
fi

# Handle relative paths -- membase always expects an absolute path.
case "$DATA_DIR" in
    /*) ;; # Already an absolute path.
    *) DATA_DIR="$PWD/$DATA_DIR";;
esac


# "Prepare" and run server.
if [ -z "$CONTINUE" ]; then
    rm -rf "$NS_DIR/"{config,data,logs,Mnesia*}
fi
"$NS_DIR/start.sh" &

# Wait for the server to accept HTTP connections.
while true; do
    curl -s "$URI_BASE" > /dev/null && break
    sleep 0.1
done

# Configure server.
# XXX: The server may need to be restarted after configuration.
curl -s "$URI_BASE"/nodes/self/controller/settings -d "path=$DATA_DIR"                                           > /dev/null
curl -s "$URI_BASE"/pools/default                  -d "memoryQuota=$RAM_QUOTA"                                   > /dev/null
curl -s "$URI_BASE"/controller/setupDefaultBucket  -d "bucketType=membase&ramQuotaMB=$RAM_QUOTA&replicaNumber=1" > /dev/null
curl -s "$URI_BASE"/settings/web                   -d 'port=SAME&username=Administrator&password=password'       > /dev/null

wait
