#!/bin/sh
#
# pt-kill	This shell script takes care of starting and stopping the pt-kill services.
#
# chkconfig:	345 60 40
#
# description: pt-kill stops long running MySQL queries
# processname:	pt-kill

# Source function library
. /etc/rc.d/init.d/functions

# Get network config
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "pt-kill"
		exit 1
	fi
else
	exit 0
fi

config=/etc/percona-toolkit/pt-kill.conf
sentinel=/var/run/percona-toolkit/pt-kill.sentinel
pidfile=/var/run/percona-toolkit/pt-kill.pid
user=percona-toolkit
# use "empty" DSN, so it uses my.cnf settings
dsn=';'

# Get service config - may override defaults
[ -f /etc/sysconfig/pt-kill ] && . /etc/sysconfig/pt-kill

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/pt-kill ]; then
		msg_already_running "pt-kill"
		return
	fi

	msg_starting "pt-kill"
	# FIXME: instead of removing, fix stop process
	rm -f $sentinel
	# use RC_LOGGING=no, because we need to escape ";" from shell
	# NOTE: disable --redirfds to be able to see connect errors
	RC_LOGGING=no \
	daemon --user $user --redirfds \
		/usr/bin/pt-kill --config $config --daemonize --pid $pidfile --sentinel $sentinel "$dsn"
	RETVAL=$?

	# workaround for lack of exit status check:
	# https://bugs.launchpad.net/percona-toolkit/+bug/1314500
	[ ! -f "$pidfile" -a $RETVAL = 0 ] && RETVAL=1

	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/pt-kill
}

stop() {
	if [ ! -f /var/lock/subsys/pt-kill ]; then
		msg_not_running "pt-kill"
		return
	fi

	# Stop daemons.
	msg_stopping "pt-kill"
	run_cmd --user $user "pt-kill" /usr/bin/pt-kill --config $config --stop --sentinel $sentinel
	# FIXME: wait for sentinel and remove it
	rm -f /var/lock/subsys/pt-kill
}

condrestart() {
	if [ ! -f /var/lock/subsys/pt-kill ]; then
		msg_not_running "pt-kill"
		RETVAL=$1
		return
	fi

	stop
	start
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  status)
	status --pidfile $pidfile pt-kill
	RETVAL=$?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
esac

exit $RETVAL
