#!/bin/bash
#
# Copyright 2014 Confluent Inc.
#
# 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.

# When stopping, search for both KafkaRestMain class and the now deprecated Main class.

APP_NAME=kafka-rest

KAFKAREST_HOME=/usr/lib/$APP_NAME

# KAFKA REST Proxy env script
. $KAFKAREST_HOME/config/kafka-rest-env.sh
#KAFKA REST Proxy PID
PID=0

#PID & LOG DIRs

[ -z $PID_DIR ] && PID_DIR="/var/run/$APP_NAME"
[ -z $LOG_DIR ] && LOG_DIR="/var/log/$APP_NAME"

#Name of PID file
PID_FILE="$PID_DIR/$APP_NAME.pid"

#Name of LOG ERR file
ERR_FILE="$LOG_DIR/$APP_NAME.err"

[ -z $MAX_WAIT_TIME ] && MAX_WAIT_TIME=120

function getPID {
   if [ ! -d $PID_DIR ]; then
      printf "Can't find pid dir.\n"
      exit 1
   fi
   if [ ! -f $PID_FILE ]; then
     PID=0
     echo "Pid file not found"
     return 1
   fi

   PID="$(<$PID_FILE)"
   echo "Pid file found"
   return 0
}

function kafkaIsRunning {
   if [ $1 -eq 0 ]; then return 0; fi

   ps -p $1 > /dev/null

   if [ $? -eq 1 ]; then
     return 0
   else
     return 1
   fi
}

function kafkaKill {
   local localPID=$1
   kill $localPID || return 1
   for ((i=0; i<MAX_WAIT_TIME; i++)); do
      kafkaIsRunning $localPID
      if [ $? -eq 0 ]; then return 0; fi
      sleep 1
   done

   kill -s KILL $localPID || return 1
   for ((i=0; i<MAX_WAIT_TIME; i++)); do
      kafkaIsRunning $localPID
      if [ $? -eq 0 ]; then return 0; fi
      sleep 1
   done

   return 1
}

function restStop {
   getPID
   kafkaIsRunning $PID
   if [ $? -eq 0 ]; then
     printf "Kafka Rest Proxy is not running.\n"
     rm -f $PID_FILE
     return 0
   fi

   printf "Stopping Kafka Rest Proxy [$PID] "
   kafkaKill $PID >>/dev/null 2>>$ERR_FILE

   if [ $? -ne 0 ]; then
     printf "failed. \n"
     exit 1
   else
     rm -f $PID_FILE
     printf "succeeded.\n"
     return 0
   fi
}

restStop
