#!/bin/bash
#
# 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.
#
# Starts a HBase rest daemon
#
# chkconfig: 345 85 15
# description: HBase rest daemon
#
### BEGIN INIT INFO
# Provides:          hbase-rest
# Short-Description: HBase rest daemon
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Required-Start:    $syslog $remote_fs
# Required-Stop:     $syslog $remote_fs
# Should-Start:
# Should-Stop:
### END INIT INFO

NAME='HBase Rest Server'
USER='{{options.user.name}}'
GROUP='{{options.group.name}}'
CONF_DIR='{{options.conf_dir}}'
RUN_DIR='{{options.pid_dir}}'
PID_FILE="${RUN_DIR}/hbase-hbase-rest.pid"
CMD="su - $USER -c \"/usr/hdp/current/hbase-client/bin/hbase-daemon.sh --config $CONF_DIR start rest\""
KILL_FORCE=0
KILL_SLEEP=10

function start {
  if [ -f $PID_FILE ]; then
    pid=`cat $PID_FILE`
    if kill -0 $pid >/dev/null 2>&1 $pid; then
       echo "$NAME already running [$pid]"
       exit 0
    else
      rm -rf $PID_FILE
    fi
  fi
  eval $CMD
  echo "$NAME running [`cat $PID_FILE`]"
}

function stop {
  kill $(<$PID_FILE) 2>/dev/null
  if [[ $? -eq 1 ]]; then
    if [[ $KILL_FORCE -eq 1 ]]; then
      sleep $KILL_SLEEP
      kill -9 $(<$PID_FILE) 2>/dev/null
      rm $PID_FILE
      echo "$NAME stopped"
    else
      echo "$NAME already stopped"
    fi
  else
    rm $PID_FILE
    echo "$NAME stopped"
  fi
}

function status {
  if [ -f $PID_FILE ]; then
    pid=`cat $PID_FILE`
    if kill -0 >/dev/null 2>&1 $pid; then
       echo "$NAME started [$pid]"
       exit 0
    fi
  fi
  echo "$NAME stopped"
  exit 3
}

if [[ $1 == "start" ]]; then
  start "$@"
elif [[ $1 == "stop" ]]; then
  stop "$@"
elif [[ $1 == "restart" ]]; then
  stop "$@"
  start "$@"
elif [[ $1 == "status" ]]; then
  status "$@"
else
  N=/etc/init.d/$NAME
  echo "Usage: $N {start|stop|restart|status}" >&2
fi
