#! /bin/sh

### BEGIN INIT INFO
# Provides:             mysql-proxy
# Required-Start:       $syslog $remote_fs
# Required-Stop:        $syslog $remote_fs
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    MySQL Proxy
### END INIT INFO

mysql_proxy=/usr/bin/mysql-proxy
config_file=/etc/mysql-proxy/mysql-proxy.conf

if ! test -x $mysql_proxy; then
	echo "Can't execute $mysql_proxy"	
	exit;
fi

start_mysql_proxy(){
	number_of_mysql_proxy_pids=`ps aux|grep -iv "grep"|grep -i "/usr/bin/mysql-proxy"|wc -l`
	if [ $number_of_mysql_proxy_pids -eq 0 ]; then
		$mysql_proxy --defaults-file=$config_file
		echo "mysql-proxy started."
	else
		echo "mysql-proxy is already running."
	fi
}

stop_mysql_proxy(){
	number_of_mysql_proxy_pids=`ps aux|grep -iv "grep"|grep -i "/usr/bin/mysql-proxy"|wc -l`
        if [ $number_of_mysql_proxy_pids -ne 0 ]; then
		mysql_proxy_pids=`pgrep mysql-proxy`
        	for mysql_proxy_pid in $(echo $mysql_proxy_pids); do
                	kill $mysql_proxy_pid 2> /dev/null
        	done

		number_of_mysql_proxy_pids=`ps aux|grep -iv "grep"|grep -i "/usr/bin/mysql-proxy"|wc -l`

        	if [ $number_of_mysql_proxy_pids -eq 0 ]; then
                	echo "mysql-proxy stopped."
        	else
                	echo "Could not stop mysql-proxy."
        	fi
	else
		echo "mysql-proxy is not running."
	fi
}


case "$1" in
    'start' )
        start_mysql_proxy
        ;;
    'stop' )
	stop_mysql_proxy
        ;;
    'restart' )
        stop_mysql_proxy
	start_mysql_proxy
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}" >&2
        ;;
esac