#!/bin/bash
# (Copyright) [2017 - 2017] Confluent, Inc.

#
# Use shellcheck to lint this file
#

# This script is mainly useful if the user has run some non-interactive query via the CLI with the
# -daemon flag passed in; it's less painful than manually grepping for the process and killing it
# However, it comes with the downside that it kills every currently-running CLI session, interactive
# or not, daemon or not, so:
# TODO: Consider only killing non-interactive and/or daemon instances of the CLI
#CLIPIDS=$(jcmd | grep 'io\.confluent\.ksql\.Ksql' | awk '{print $1}')
CLIPIDS=$(ps aux | grep 'io\.confluent\.ksql\.Ksql' | awk '{print $2}')

if [ -z "$CLIPIDS" ]; then
  echo "No CLI session(s) to stop"
  exit 0
fi

for PID in $CLIPIDS; do
  kill -s TERM "$PID"
  for ((i=0; i<10; i++)); do
    kill -0 "$PID"
    if [ $? -eq 0 ]; then sleep 1; continue; fi
  done
  sleep 5
  kill -9 "$PID"
done
