#!/bin/sh

start_ts=$(date +%s)

PIDFILE="TMP_DIR/PORT/data/mysql_sandboxPORT.pid"
SOCKETFILE="TMP_DIR/PORT/mysql_sandboxPORT.sock"
BASEDIR="PERCONA_TOOLKIT_SANDBOX"

sandbox_is_alive() {
   # First, all these files must exist.
   [ -f $PIDFILE -a  -S $SOCKETFILE ] || return 1

   # And that PID file must have a PID.
   local pid=$(cat TMP_DIR/PORT/data/mysql_sandboxPORT.pid 2>/dev/null)
   [ "$pid" ] || return 1

   # Second, MySQL is truly alive when it respond to a ping.
   # It's not enough that the mysqld process is running because
   # InnoDB can take time to create ibdata1, etc.  So MySQL is
   # only alive when it responds to queries.
   $BASEDIR/bin/mysqladmin --defaults-file="TMP_DIR/PORT/my.sandbox.cnf" ping >/dev/null 2>&1
   [ $? -eq 0 ] || return 1

   return 0
}

_seq() {
   local i="$1"
   awk "BEGIN { for(i=1; i<=$i; i++) print i; }"
}

# #############################################################################
# Script starts here
# #############################################################################

echo -n "Stopping MySQL test server on port PORT... "

if sandbox_is_alive; then
   $BASEDIR/bin/mysqladmin --defaults-file=TMP_DIR/PORT/my.sandbox.cnf shutdown
fi

for i in $(_seq 60); do
   if sandbox_is_alive; then
      sleep 1
      continue
   fi
   rm -rf $PIDFILE 2>/dev/null
   rm -rf $SOCKETFILE 2>/dev/null
   end_ts=$(date +%s)
   t=$((end_ts - start_ts))
   echo "OK (${t}s)"
   exit 0
done

end_ts=$(date +%s)
t=$((end_ts - start_ts))
echo "FAILED (${t}s)"
exit 1
