#!/usr/bin/env bash
#
# vim:et:ft=sh:sts=2:sw=2
#
#/**
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements.  See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership.  The ASF licenses this file
# * to you 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.
# */

function show_help() {
  cat <<EOF
Usage: standalone.process [-c <cluster_name>] [-h] <action:[up|down]>
EOF
}

BINDIR=${BK_BINDIR:-"`dirname "$0"`"}

source ${BINDIR}/common.sh

DATA_ROOT_DIR=${BK_DATA_DIR:-"${BK_HOME}/data"}
mkdir -p ${DATA_ROOT_DIR}

# main entrypoint

CLUSTER_NAME="bk-standalone"
OPTIND=1

while getopts "h:c:" opt; do
  case "${opt}" in
  c )
    CLUSTER_NAME=${OPTARG}
    echo "use cluster = '${CLUSTER_NAME}'."
    ;;
  h|\? )
    show_help
    exit 1
    ;;
  esac
done

shift $((OPTIND-1))

[ "${1:-}" = "--" ] && shift

if [ $# -le 0 ]; then
  show_help
  exit 1
fi

ACTION=$1
DAEMON_ACTION=""
case "${ACTION}" in
  up)
    DAEMON_ACTION="start"
    ;;
  down)
    DAEMON_ACTION="stop"
    ;;
  *)
    echo "Unknown action : ${ACTION}"
    show_help
    exit 1
    ;;
esac


CLUSTER_DATA_ROOT="${DATA_ROOT_DIR}/${CLUSTER_NAME}"
mkdir -p ${CLUSTER_DATA_ROOT}

${BINDIR}/bookkeeper-daemon.sh ${DAEMON_ACTION} standalone --data-dir ${CLUSTER_DATA_ROOT}
