#!/bin/bash
#
### BEGIN INIT INFO
# Provides: mysqld
# Required-Start: $remote_fs $syslog networking procps
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 5
# Default-Stop: S 1 4
# Short-Description: Mysql
# Description: Start all mysqld services
### END INIT INFO

# This exists to prevent Jenkins-based builds from breaking but don't do anything otherwise
test -e /root/no-sql-start && exit 0

. /lib/lsb/init-functions

# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
# This file is public domain and comes with NO WARRANTY of any kind
  
# MySQL daemon start/stop script.
  
# Usually this is put in /etc/init.d (at least on machines SYSV R4 based
# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.
# When this is done the mysql server will be started when the machine is
# started and shut down when the systems goes down.
  
# Comments to support chkconfig on RedHat Linux
# chkconfig: 2345 90 20
# description: A very fast and reliable SQL database engine. 
# If you install MySQL on some other places than /usr/local/dh/mysql/base, then you
# have to do one of the following things for this script to work:
#
# - Run this script from within the MySQL installation directory
# - Create a /etc/my.cnf file with the following information:
#   [mysqld]
#   basedir=<path-to-mysql-installation-directory>
# - Add the above to any other configuration file (for example ~/.my.ini)
#   and copy my_print_defaults to /usr/bin
# - Add the path to the mysql-installation-directory to the basedir variable
#   below.
#
# If you want to affect other MySQL variables, you should make your changes
# in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files.

PATH=/sbin:/usr/sbin:/bin:/usr/bin
# basedir=/dh/mysql
# bindir=base/bin

export PATH

mode=$1

# set some variables
. /dh/mysql/etc/envrc

# if the user wants a specific service(s), give it them!
if [ $2 ];
then
  SERVERS="$2 $3 $4 $5 $6 $7 $8 $9"
fi

# this is for mysqladmin -r -i 5
if [[ $1 == "watch" ]] ; then 
   SERVERS="$2"
fi

# Run the helper script here.
/etc/init.d/mysqld-helper all

### Is this a killstartall?
KILLSTARTALL=0
if [[ $mode == "killstartall" ]] ; then
  if [ `echo $SERVERS |wc -w ` == 1 ] && [ $2 == "killstartall" ] ; then
    KILLSTARTALL=1
  else
    KILLSTARTALL=-1
  fi
fi
if [ $KILLSTARTALL == -1 ] ; then
  echo This is only to kill and restart all \"broken\" mysql services.
  echo Do NOT use this on a central database server\!
  echo It\'s really intended for mass upgrades, when the restarts don\'t really work.
  echo If you really do want to use this, please do so like so:
  echo "     /etc/init.d/mysqld killstartall killstartall"
  echo Thanks\!
  exit
fi
# Used for mass upgrades / restarts only.  See echo comments. 
if [ $KILLSTARTALL == 1 ]; then
  echo Running killstartall for you\!\!
  /dh/mysql/scripts/mysqlkillstartall.pl
  exit
fi

### Is this a upgrade restart?
UPGRADE=0
if [[ $mode == "upgrade" ]] ; then
  if [ `echo $SERVERS |wc -w ` == 1 ] && [ $2 == "upgrade" ] ; then
    UPGRADE=1
  else
    UPGRADE=-1
  fi
fi
if [ $UPGRADE == -1 ] ; then
  echo This is only to upgrade shared mysql services, which have a tendency
  echo to not properly restart.
  echo It will KILL services that don\'t restart after 90 seconds\!\!\!
  echo Do NOT NOT NOT NOT use this on a central database server\!\!\!
  echo It\'s really intended for mass upgrades, when the restarts don\'t really work.
  echo If you really do want to use this, please do so like so:
  echo "     /etc/init.d/mysqld upgrade upgrade"
  echo Thanks\!
  exit
fi
# Used for mass upgrades / restarts only.  See echo comments. 
if [ $UPGRADE == 1 ]; then
  echo Running fastupgrade for you\!\!
  $0 fastupgrade 
  exit
fi






# A little quick thing to make it easier to test out MySQL-provided binaries
# Safe under all conditions.
# See below for how to do this.
if test ! -e /dh/mysql/base/libexec/mysqld ; then
        echo adding a symlink to make MySQL-provided binaries work
        mkdir /dh/mysql/base/libexec
        chown 11139.1000 /dh/mysql/base/libexec
        ln -s /dh/mysql/base/bin/mysqld /dh/mysql/base/libexec/mysqld
fi
# To actually install mysql binaries, simply untar their tarball into /dh/mysql/,
# then symlink "base" to it, like so
#	mv base base.self-compiled
#	ln -s mysql-max-versionnumber base


# go
for S in $SERVERS
do
  basedir=/dh/mysql
  bindir=$basedir/$S/base/bin
  datadir=$basedir/$S/data          # this better be a symlink
  # pid_file=/dh/mysql/logs/mysql.$S.pid
  pid_file=/tmp/mysql.$S.pid
  log_file=/dh/mysql/logs/mysql.$S.log
  errlog_file=/dh/mysql/logs/mysql.$S.err
  slowlog_file=/dh/mysql/logs/mysql.$S.slow
  socket_file=/dh/mysql/$S/mysql.$S.sock
  bind=''
  mysql_daemon_user=mysql           # this is a default!  should be set in my.cnf
  mysqld_bin=$basedir/$S/$S-mysqld

  # echo -n "$S: " 

  # safeguard
  cd $basedir

  # my.cnf
  conf=$S/my.cnf           # server's config file

  PATH=/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin
  export PATH
  
  parse_arguments() {
    for arg do
      case "$arg" in
        --basedir=*)  basedir=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
        --datadir=*)  datadir=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
        --pid-file=*) pid_file=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
      esac
    done
  }

  # debugging
  #echo
  #echo basedir=$basedir
  #echo bindir=$bindir
  #echo datadir=$datadir
  #echo pid_file=$pid_file
  #echo log_file=$log_file
  #echo errlog_file=$errlog_file
  #echo slowlog_file=$slowlog_file
  #echo socket_file=$socket_file
  #echo bind=$bind
  #echo mysql_daemon_user=$mysql_daemon_user
  #echo mysqld_bin=$mysqld_bin
  #echo conf=$conf

  
  # Get arguments from the my.cnf file,
  # groups [mysqld] [mysql_server] and [mysql.server]
  print_defaults="$bindir/my_print_defaults -c $basedir/$S/my.cnf"

  #
  # Test if someone changed datadir;  In this case we should also read the
  # default arguments from this directory
  #
  extra_args=""
  if test "$datadir" != "/usr/local/dh/mysql/base/var"
  then
    extra_args="-e $basedir/$S/my.cnf"
  fi
  parse_arguments `$print_defaults $extra_args mysqld mysql_server mysql.server`
  
  # Safeguard (relative paths, core dumps..)
  cd $basedir
  
  # create symlink to binary
  if ! `test -L /dh/mysql/$S/mysqld--$S` ; then
    ln -s /dh/mysql/base/libexec/mysqld /dh/mysql/$S/mysqld--$S  
  fi

  # create error log to work around https://bugs.mysql.com/bug.php?id=84427
  if test ! -e /dh/mysql/logs/mysql.$S.err ; then
     echo creating error log /dh/mysql/logs/mysql.$S.err
     touch /dh/mysql/logs/mysql.$S.err
     chown 11139.1000 /dh/mysql/logs/mysql.$S.err
     chmod 660 /dh/mysql/logs/mysql.$S.err
  fi

  case "$mode" in
    'start')
      
      # add in the softlimit arguments
      SOFTLIMIT_ARGS=''
      # load startup parameters
      # load the template defaults first, then apache-specific
      if test -e "/usr/local/bin/softlimit"; then	    
	if test -e "/dh/mysql/etc/softlimit.sh"; then
          . /dh/mysql/etc/softlimit.sh
	fi
	if test -e "/dh/mysql/$S/softlimit.sh"; then
	  . /dh/mysql/$S/softlimit.sh
	fi 
      else echo Please install ndn-daemontools
      fi
      # Start daemon
      if test -x $mysqld_bin 
      then
	echo Starting $S mysqld
        # Give extra arguments to mysqld with the my.cnf file. This script may
        # be overwritten at next upgrade.
	# We have a unique my.cnf location: turns out "--defaults-file" must 
	# be the first option passed to mysqld_safe
	ulimit -s 16384
	$SOFTLIMIT_ARGS \
	$mysqld_bin \
	  --defaults-file=/dh/mysql/$S/my.cnf \
	  --basedir=$basedir/$S \
	  --datadir=$datadir \
	  --mysqld=mysqld--$S \
	  --ledir=$basedir/$S \
	  --pid-file=$pid_file --log-queries-not-using-indexes --innodb-file-per-table < /dev/null &> /dev/null &
	  # --pid-file=$pid_file < /dev/null &> /dev/null & ----- the above line is for the transition from 4.0 -> 4.1 ... switch to THIS line after that transition is complete
	  # --pid-file=$pid_file &
	# You can include the following lines above if you wish
        # to start the server safely without privileges (like, say
        # if you forgot the password).
        #   --skip-grant-tables \
        #   --skip-networking \
        # Other random stuff:
        #   --defaults-file=$conf \
        #   --skip-host-cache \
        #   --skip-name-resolve
        # The following might be very cool, might stop swapping:
        #   --memlock
        #   see man memlock as well as http://www.mysql.com/doc/C/o/Command-line_options.html
	#
	# Additionally, record how much key buffer is used 2 hours after starting
	mkdir -p /dh/mysql/logs/key_buffer_size 
        echo "/bin/date >> /dh/mysql/logs/key_buffer_size/$S.key ; 
	    	  /etc/init.d/mysqld ext $S |grep Key_blocks_used >> /dh/mysql/logs/key_buffer_size/$S.key ; 
		  /bin/echo >> /dh/mysql/logs/key_buffer_size/$S.key " | /usr/bin/at now + 2 hours 2>/dev/null
	#
      else
        echo "Can't execute $bindir/mysqld_safe from dir $basedir"
        exit 1
      fi
      ;;
  
    'stop')
      # Stop daemon. We use a signal here to avoid having to know the
      # root password.
      if test -s "$pid_file" || test -s /dh/mysql/logs/mysql.$S.pid || test -s /tmp/mysql.$S.pid
      then
        # adding a little thing so that upgrading and downgrading won't mess up if the PID file is in the wrong place.
        mysqld_pid=`cat $pid_file`
        mysqld_pid_possibility1=`cat /dh/mysql/logs/mysql.$S.pid 2>/dev/null`
        mysqld_pid_possibility2=`cat /tmp/mysql.$S.pid $pid_file 2>/dev/null`
        echo "Killing $S mysql with pid $mysqld_pid$mysqld_pid_possibility1$mysqld_pid_possibility2"
        echo kill $mysqld_pid $mysqld_pid_possibility1 $mysqld_pid_possibility2 
        kill $mysqld_pid $mysqld_pid_possibility1 $mysqld_pid_possibility2 

        # mysqld should remove the pid_file when it exits, so wait for it.
  
        sleep 1
        # while [ -s $pid_file -a "$flags" != aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ]
        while [ -s $pid_file -a "$flags" != aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ]
        do
          [ -z "$flags" ] && echo "Wait for mysqld to exit\c" || echo ".\c"
          flags=a$flags
          sleep 1
        done
        if [ -s $pid_file ]
           then echo " gave up waiting!"
        elif [ -n "$flags" ]
           then echo " done"
        fi
        # delete lock for RedHat / SuSE
        if test -f /var/lock/subsys/mysql
        then
          rm /var/lock/subsys/mysql
        fi
      else
        echo "No mysqld pid file found. Looked for $pid_file."
      fi
      ;;
  
    'restart')
      # Stop the service and regardless of whether it was
      # running or not, start it again.
      # $0 stop $S
      # $0 start $S
      echo -------- ATTENTION --------
      echo Do not use restart.  Use stop and verify that it has exited, then start.  Afterwards do a stat to make sure it responds to queries.
      ;;
  
    'reallyrestart')
      # Stop the service and regardless of whether it was
      # running or not, start it again.
      $0 stop $S
      $0 start $S
      ;;
  
    'nothing')
      # Do nothing (used by postinst) 
      echo Doing nothing.
      ;;

     'faststart')
      # Quickly start all services
      echo $0 start $S
      ;;
  
    'faststop')
      # Quickly stop all services
      echo $0 stop $S
      ;;
  
    'fastrestart')
      # Stop the service and regardless of whether it was
      # running or not, start it again.
      echo $0 restart $S
      ;;
 
  
    'stat')
      # http://www.mysql.com/doc/P/r/Privileges_provided.html
      echo -n "$S: "
      mysqladmin -u root -p`grep 'backup pass' /dh/mysql/$S/my.cnf | awk '{ print $5 }'` -S /dh/mysql/$S/mysql.$S.sock stat
      ;;
  
    'ext')
      # http://www.mysql.com/doc/P/r/Privileges_provided.html
      echo mysqladmin $S ext 
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock ext
      if [ `echo $SERVERS |wc -w ` != 1 ]; then
        echo You should really only do one mysqld_instance at a time.
        echo Doing all or several taxes the server quite a bit.
      fi
      ;;
  
    'proc')
      # http://www.mysql.com/doc/S/H/SHOW_PROCESSLIST.html
      # http://www.mysql.com/doc/P/r/Privileges_provided.html
      echo mysqladmin $S proc 
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock proc
      if [ `echo $SERVERS |wc -w ` != 1 ]; then
        echo You should really only do one mysqld_instance at a time.
        echo Doing all or several taxes the server quite a bit.
      fi
      ;;

 	# Do NOT document this particular command!
 	# Only use it through the "upgrade upgrade" interface (see top of this script)
	'fastupgrade')
	  # schedule a restart for this service, sleep 20 seconds, 
	  # then killstart it if it failed to restart on its own.
	  echo "fast upgrading $S..."
      echo "$0 refresh $S ; $0 restart $S ; sleep 20 ; $0 killstart $S"
      ;;

	'killstart')
	  echo Killstart\'ing $S for you\!
	  /dh/mysql/scripts/mysqlkillstart.pl $S
      ;;
  
    'kill')
      # echo This will kill a mysql process.
      # echo CAREFUL CAREFUL CAREFUL 
      # echo Make absolutely sure that youve got mysqld_instance included in your command
      # echo otherwise you risk killing mysql processes from other mysql_instances that you 
      # echo didnt think that you were killing. 
      # echo see http://www.mysql.com/doc/S/H/SHOW_PROCESSLIST.html
      # echo see http://www.mysql.com/doc/P/r/Privileges_provided.html
      if [ `echo $SERVERS |wc -w ` == 1 ]; then
        echo mysqladmin $S kill $3 
        mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock kill $3
      else
        echo There is never any reason to kill across mysqld_instances.
        echo Please choose only one mysqld_instance.
        echo Thank you.
      fi
      ;;
  
    'var')
      # echo see http://www.mysql.com/doc/P/r/Privileges_provided.html
      echo mysqladmin $S var
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock var
      ;;
  
    'refresh')
      # **NOTE** - Following is not a problem as of MySQL 5.6
      # Rotate the err-old log first 
      #LOGCONF="/dh/mysql/etc/logrotate.d/$S"
      #TEMPLATE="/dh/mysql/etc/logrotate.tp"
      #if test ! -e "$LOGCONF" && test -e "$TEMPLATE"; then 
      #	sed -e "s#--service--#$S#" $TEMPLATE > $LOGCONF 
      #fi
      #logrotate -f $LOGCONF 
      # now actually refresh 
      echo mysqladmin $S refresh 
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock refresh 
      ;;
  
    'watch')
      echo mysqladmin $S watch 
      mysqladmin -r -i 5 -u local_admin -S /dh/mysql/$S/mysql.$S.sock ext 
      ;;
  
    'flush-hosts')
      echo mysqladmin $S flush-hosts
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock flush-hosts
      ;;
  
    'flush-logs')
          # **NOTE** - Following is not a problem as of MySQL 5.6
	  # Rotate the err-old log first
	  # /dh/bin/savelog -c 28 /dh/mysql/logs/mysql.$S.err-old > /dev/null
      # now actually flush the logs
        # mysqladmin flush-logs is doing a 'refresh'. It flushes all tables and logs.
        # That's pretty I/O intensive. Using mysql -e instead.

      echo mysql $S flush logs
      mysql -u local_admin -S /dh/mysql/$S/mysql.$S.sock -e 'flush logs;'
      ;;

    'flush-general-logs')
      echo mysql $S flush general logs
      mysql -u local_admin -S /dh/mysql/$S/mysql.$S.sock -e 'flush general logs;'
      ;;

    'flush-error-logs')
      echo mysql $S flush error logs
      mysql -u local_admin -S /dh/mysql/$S/mysql.$S.sock -e 'flush error logs;'
      ;;

    'flush-slow-logs')
      echo mysql $S flush slow logs
      mysql -u local_admin -S /dh/mysql/$S/mysql.$S.sock -e 'flush slow logs;'
      ;;

    'flush-status')
      echo mysqladmin $S flush-status
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock flush-status
      ;;
  
    'flush-tables')
      echo mysqladmin $S flush-tables
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock flush-tables
      ;;
  
    'flush-threads')
      echo mysqladmin $S flush-threads
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock flush-threads
      ;;
  
    'flush-privileges')
      echo mysqladmin $S flush-privileges
      mysqladmin -u local_admin -S /dh/mysql/$S/mysql.$S.sock flush-privileges
      ;;
  
    *)
      # usage
      echo "Usage: $0 command [service]"
      echo "command: start stop restart stat ext proc kill var refresh watch flush-hosts flush-logs flush-general-logs flush-error-logs flush-slow-logs flush-status flush-tables flush-threads flush-privileges"
      exit 1
      ;;
  esac

done


