#!/bin/ksh

# Component: mysql
#
# Description:
#  Control script of component mysql
#
# MYSQL_PID : created and deleted by mysqld; contains the PID of the mysqld process
# MYSQL_RUN : indicates whether the mysqld process should run or not
#             will be created by mysqldw when starting mysqld and removed in ctrl stop
#
# Last Updated     : $Author$
# Update Date Time : $Date$
# RCS File Name    : $RCSfile$
# RCS Revision     : $Revision$
# Locked by        : $Locker$
# Symbolic name    : $Name$
# State            : $State$

#--- INIT ------------------------------
#needs $HOME
. $HOME/etc/ctrl.main.shi
. /etc/erad-base/setenv.sh

[ -f $HOME/etc/setenv.sh ] && . $HOME/etc/setenv.sh

# We have to handle then situation, when MySQLD works in remote mode, MYSQL_UNIX_PORT is 
# set to REMOTE in setenv.sh, but it's still in the inhertied environment.
# But MYSQLD_MODEis set the right way in setenv.sh
if [ "$MYSQLD_MODE" == 'REMOTE' ]; then
	unset MYSQL_UNIX_PORT
	export MYSQL_UNIX_PORT
fi

#--- FUNC ------------------------------
do_shell_()
{
	# Recognize these variables from virthost.sh
	local MYSQL_TCP_PORT;	# Mysqld tcp port to bind (server) and connect (client)
	local MYSQL_HOST;		# Mysqld host name or IP and connect (server and client)
	local MYSQL_BIND;		# Mysqld host IP to bind (server)
	local MYSQL_UNIX_PORT;	# Mysqld unix socket to create  (server) and connect (client)
	local MYSQL_USER;		# Mysqld should connect as this user (client)
	local MYSQL_PASSWORD;	# Mysqld should connect with this password (client)
	local DBNAME;			# Database name to use

	# Generate these variables based on virthost.sh, installed components
	local MYSQL_DB_USER;	# Mysqld shall create database file with this user
	local MYSQL_MODE;	    # Which mysql to use: EMBEDDED|SYSTEM (client)
	local MYSQLD_MODE;	    # Which mysqld to use EMBEDDED|SYSTEM|REMOTE (server)
	local MYSQL_VAR;		# Parsed mysql config templates in a drop in config dir
	local MYSQL_CONFD;		# Actual drop-in config dir used
	local MYSQL_BINDIR; 	# Location of the mysql client binaries
	local MYSQL_ROOT_PW;	# Mysql root user password
	local MYSQL_CLIENT;	    # Mysql server should recognise us as this IP/hosname/FQDN
	local MYSQL_LOGDIR;		# Mysql log directory
	local MYSQL_BASEDIR;	# Mysql basedir parameter

	# Load virthost config. We expect MYSQL_UNIX_PORT MYSQL_TCP_PORT MYSQL_USER MYSQL_PASSWORD DBNAME MYSQL_HOST MYSQL_BIND 
	if [ -f "$ETC/virthost.sh" ]; then
		. "$ETC/virthost.sh"
	fi

	# Check if remote mode was specified
	local unixPort=$(echo -n "$MYSQL_UNIX_PORT" | tr [:lower:] [:upper:])

	# Check for mysql and client binary, if it's a file this is embedded.
	if [ -f $HOME/component/mysql/bin/mysql -a ! -L $HOME/component/mysql/bin/mysql ]; then
		# We use local mysql client
		MYSQL_MODE='EMBEDDED'
		MYSQL_BINDIR="$MYSQL_HOME/bin"
		MYSQL_LOGDIR="$LOG"
		MYSQL_BASEDIR=$MYSQL_HOME
                MYSQL_LCMESSAGES_DIR=$MYSQL_HOME/share
		
		# Check what was configured in virthost.sh
		if [ "$unixPort" == "REMOTE" ]; then
			# Remote mode was specified, don't handle mysql and do not init database
			MYSQLD_MODE='REMOTE'
		else
			# Default mode, handle mysqld and init database
			MYSQLD_MODE='EMBEDDED'
		fi
	else
		if [ -x "$sys_mysqlbindir/mysql" -a -x "$sys_mysqlbindir/mysqladmin" -a -x "$sys_mysqlbindir/mysqlshow" -a -x "$sys_mysqlbindir/mysqldump" ] ; then
			# We use system mysql client
			MYSQL_MODE='SYSTEM' 
			MYSQL_BINDIR="$sys_mysqlbindir"
			MYSQL_LOGDIR="/var/log"
			MYSQL_BASEDIR="/usr"
                        MYSQL_LCMESSAGES_DIR="/usr/share/mysql"
		else
			echo "Fatal error! Neither embedded, nor system-installed mysql client found! " >&2
			return 127
		fi

		mkdir -p "$MYSQL_HOME/bin"
		# Create compatibility symlinks here .We can't wait with this, because it may be used
		for symlink in innochecksum msql2mysql myisamchk myisam_ftdump myisamlog myisampack \
		my_print_defaults mysql mysqlaccess mysqlaccess.conf mysqladmin mysqlbinlog mysqlbug \
		mysqlcheck mysql_config mysql_config_editor mysql_convert_table_format \
		mysqld mysqld_multi mysqld_safe mysqldump mysqldumpslow mysql_find_rows mysql_fix_extensions \
		mysqlhotcopy mysqlimport mysql_plugin mysql_secure_installation \
		mysqlshow mysqlslap mysqltest mysql_tzinfo_to_sql mysql_upgrade mysql_waitpid mysql_zap \
		perror replace resolveip resolve_stack_dump; do
			# Look for target executable in path
			local TARGET=$(bash -c "type -p $symlink")
			if [ -n "$TARGET" ]; then
				# Double check
				if [ -h "$MYSQL_HOME/bin/$symlink" ]; then
					# Clean up the old
					rm -f "$MYSQL_HOME/bin/$symlink"
				else
					[ -e "$MYSQL_HOME/bin/$symlink" ] && echo "Fatal error: '$MYSQL_HOME/bin/$symlink' exist and not a symlink!" >&2
				fi
			else
				echo "Warning: Can't locate target binary for '$MYSQL_HOME/bin/$symlink' symlink!" >&2
				continue
			fi	
			# Create the new
			ln -s "$TARGET" "$MYSQL_HOME/bin/$symlink"
		done
		
		# Check what was configured in virthost.sh
		if [ "$unixPort" == "REMOTE" ]; then
			# Remote mode was specified, don't handle mysql and do not init database
			MYSQLD_MODE='REMOTE'
		else
			# Default mode, handle mysqld and init database
			MYSQLD_MODE='SYSTEM'
		fi
	fi

	# Set default parameters if not specified in virthost.sh
	[ -z "$MYSQL_TCP_PORT" ] && MYSQL_TCP_PORT=`if [ develop = \$USER ]; then echo 2907; else echo 3306; fi`
	[ -z "$MYSQL_HOST" -a "$MYSQLD_MODE" != 'REMOTE' ] && MYSQL_HOST='localhost'
	[ -z "$MYSQL_BIND" -a "$MYSQLD_MODE" != 'REMOTE' ] && MYSQL_BIND='127.0.0.1'
	[ -z "$MYSQL_USER" ] && MYSQL_USER="$MED_USER"
	[ -z "$DBNAME" ] && DBNAME='imagemedical'
	[ -z "$MYSQL_ROOT_PW" ] && MYSQL_ROOT_PW='ec3tera'
		
	# Generate variables common in all mysql/mysqld mode
	cat <<-EndOfInlineData
	MYSQL_MODE=$MYSQL_MODE
	MYSQLD_MODE=$MYSQLD_MODE
	MYSQL=\$HOME/component/mysql
	MYSQL_HOME=\$HOME/component/mysql
	DBMODE=msq:
	INDEXTBL=Dcindex
	ACCESSTBL=Access
	TARGETTBL=Target
	GROUPSTBL=UGroups
	MYSQL_TCP_PORT=$MYSQL_TCP_PORT
	MYSQL_VAR=\$VAR/mysql_conf
	MYSQL_BINDIR="$MYSQL_BINDIR"
	DBNAME=$DBNAME
	MYSQL_ROOT_PW=$MYSQL_ROOT_PW
	MYSQL_LOGDIR=$MYSQL_LOGDIR
	MYSQL_BASEDIR=$MYSQL_BASEDIR
        MYSQL_LCMESSAGES_DIR=$MYSQL_LCMESSAGES_DIR
	EndOfInlineData

	if [ "$MYSQL_MODE" == 'EMBEDDED' ]; then
		cat <<-EndOfInlineData
		MYSQL_CONFD=\$MYSQL_VAR
		EndOfInlineData
	else
		cat <<-EndOfInlineData
		MYSQL_CONFD=$sys_mysql_conf_d
		EndOfInlineData
	fi

	# Generate variables based on mysql mode.
	if [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
		# This is legacy mode. Use embedded mysql.
		cat <<-EndOfInlineData
		MYSQL_UNIX_PORT="\$HOME/var/mysql.sock"
		MYSQL_USER=\$MED_USER
		MYSQL_DB_USER=\$MED_USER
		MYSQL_DATA=\$HOME/var/mysql
		MYSQL_RUN=\$RUN/mysqld.run
		MYSQL_PID=\$RUN/mysql.pid
		MYSQL_BIND=$MYSQL_BIND
		MYSQL_HOST=$MYSQL_HOST
		MYSQL_CLIENT="$MYSQL_CLIENT"
		EndOfInlineData
	elif [ "$MYSQLD_MODE" == 'SYSTEM' ]; then
		# In this mode we use system installed mysql. 
		# Client software will pick up config and server config is synced.
		cat <<-EndOfInlineData
		MYSQL_UNIX_PORT=$sys_mysqld_socket
		MYSQL_USER=\$MED_USER
		MYSQL_DB_USER=$sys_mysql_user
		MYSQL_DATA=\$HOME/var/mysql
		MYSQL_RUN=$sys_mysql_run
		MYSQL_PID=$sys_mysql_pid
		MYSQL_BIND=$MYSQL_BIND
		MYSQL_HOST=$MYSQL_HOST
		MYSQL_CLIENT="$MYSQL_CLIENT"
		EndOfInlineData
	elif [ "$MYSQLD_MODE" == 'REMOTE' ]; then
		# In remote mode we try to connect to an external mysql server and use system mysql client.
		# Database name (has default) and password (no default) is optional
		
		[ -n "$MYSQL_USER" ] &&  echo "MYSQL_USER=$MYSQL_USER"
		[ -n "$MYSQL_PASSWORD" ] &&  echo "MYSQL_PASSWORD=$MYSQL_PASSWORD"

		# Mysql server must be specified
		if [ -n "$MYSQL_HOST" ]; then
			echo "MYSQL_HOST=$MYSQL_HOST"
		else 
			echo -e "Error! Mysql server must be specified in ~/etc/virthost.sh (MYSQL_HOST=<...>)!" >&2
			exit 127
		fi
		
		#Mysql client data must be specified
		if [ -n "$MYSQL_CLIENT" ]; then
			echo "MYSQL_CLIENT=\"$MYSQL_CLIENT\""
		else
			echo -e "Error! At least one of the mysql client hostname, IP or FQDN must be specified in ~/etc/virthost.sh (MYSQL_CLIENT='<...> [<...>]')" >&2
			exit 127
		fi
	fi

} #do_shell_()


#
# Printing new entries from startup log file to standard out
#
# $1 - path to startup log file
#
# env:
#  lastLineNum : line number of the last line printed to stdout
#
print_startup_log ()
{
	local logFile="$1"
	local lineNum;
	local newLines;
	local startLine;

	lineNum=`cat $logFile | wc -l`
	newLines=$(( $lineNum - $lastLineNum ))
	if [ $newLines -gt 0 ] ; then
		startLine=$(( lastLineNum + 1 ))
		tail -n +$startLine $logFile | head -n $newLines
		lastLineNum=$lineNum
	fi
}

start_daemon()
{
	if [ "$MYSQLD_MODE" == 'REMOTE' ]; then
		# We don't start anything in remote mode
		return 0
	elif [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
		if do_status_ > /dev/null 2>&1; then
			echo "Component MySQL already running"
			return 0
		fi
	elif [ "$MYSQLD_MODE" == 'SYSTEM' ]; then
		if sudo /sbin/service mysqld status > /dev/null 2>&1; then
		    if [ $is_new_db -eq 1 ]; then
			sudo /sbin/service mysqld stop > /dev/null 2>&1
		    else
			echo "System MySQL already running"
			return 0
		    fi
		fi
	fi

	if [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
		# first remove MYSQL_PID if exists, because mysql doesn't handle
		# correctly existing pid files
		[ -f "$MYSQL_PID" ] && rm $MYSQL_PID 2>/dev/null
		
		touch $RUN/mysql.startup
		[ -f "$LOG/mysql.startup.log" ] && rm "$LOG/mysql.startup.log"

		echo "Starting component mysqld..."
		$MYSQL_HOME/mysqldw 2>&1 | tee $LOG/mysql.startup.log >>$LOG/mysql.log 2>&1 &

		# save the pid of the wrapper started (well, it's the pid of tee)
		local mysqldwPid=$!
		
		#
		# Waiting for mysqld do the initialization and start
		#
		local lastLineNum=0

		while [ -n "$(ps -p $mysqldwPid -o comm=)" ] ; do
			# The wrapper is still running

			# check if mysqld is up
			if $MYSQL_HOME/bin/mysqlshow >/dev/null 2>&1 ; then
				# The mysqld is up and listening
				# remove the startup flag and exit the loop
				rm "$RUN/mysql.startup" 2>/dev/null

				print_startup_log "$LOG/mysql.startup.log"
				return 0;
			fi

			#
			# Print new entries from mysqld output to standard out
			#

			print_startup_log "$LOG/mysql.startup.log"

			sleep 1
		done

		print_startup_log "$LOG/mysql.startup.log"
		return 1
	elif [ "$MYSQLD_MODE" == 'SYSTEM' ]; then
				echo "Starting system mysqld..."

		# Start up system mysql service.
		sudo /sbin/service mysqld start > /dev/null 2>&1
	fi
} #start_daemon()


#
# Generate factory default config files from templates
#
# $1 - the template file
# $2 - path to the config file to generate
#
gen_cnf_file ()
{
	local templateFile="$1"
	local configFile="$2"
	local TMP_DIR
	
	if [ "$MYSQLD_MODE" == "EMBEDDED" ]; then
	    TMP_DIR="$TMP"
	    printMsg="MySQL tmpdir will be set to \e[36m$TMP\e[0m"
	else
	    if [ -d /home/mysql/tmp ]; then
		homemysql_free=$(df /home/mysql|tail -1|awk '{print $4}')
		tmp_free=$(df /tmp|tail -1|awk '{print $4}')
		if (( $(echo "$tmp_free > $homemysql_free"|bc -l) )); then
			TMP_DIR='/tmp'
			printMsg="\e[31mWARNING: MySQL tmpdir will be set to /tmp because it has more free space (${tmp_free}) than /home/mysql/tmp (${homemysql_free})\e[0m"
		else
			TMP_DIR='/home/mysql/tmp'
			printMsg="MySQL tmpdir will be set to \e[36m/home/mysql/tmp\e[0m"
		fi
	    else
		TMP_DIR='/tmp'
		printMsg="\e[31mWARNING: MySQL tmpdir will be set to /tmp because /home/mysql/tmp does not exists\e[0m"
	    fi
	fi
	
	tmpdirOverride=$(grep '^tmpdir=' ~/var/conf/mysql.cnf|cut -d= -f2)
	if [ -n "$tmpdirOverride" ]; then
	    printMsg="Mysql tmpdir is set to \e[36m${tmpdirOverride}\e[0m in ~/var/conf/mysql.cnf\e[0m"
	fi
	

	if [ -n "$printMsg" -a "$templateFile" == "/home/medsrv/component/mysql/config/2server-common.cnf.in" ]; then
	    echo -e "$printMsg"
	fi
	
	
	# Replace macros in config files
	sed -e "s;@MYSQL_TCP_PORT@;$MYSQL_TCP_PORT;g
			s;@MYSQL_UNIX_ADDR@;$MYSQL_UNIX_PORT;g
			s;@MYSQL_UNIX_PORT@;$MYSQL_UNIX_PORT;g
			s;@MYSQL_HOST@;$MYSQL_HOST;g
			s;@MYSQL_USER@;$MYSQL_USER;
			s;@MYSQL_PID@;$MYSQL_PID;g
			s;@MYSQL_RUN@;$MYSQL_RUN;g
			s;@HOME@;$HOME;g
			s;@MYSQL_CONFD@;$MYSQL_CONFD;g
			s;@MYSQL_VAR@;$MYSQL_VAR;g
			s;@TMP_DIR@;$TMP_DIR;g
			s;@MYSQL_BIND@;$MYSQL_BIND;g
			s;@MYSQL_BINDIR@;$MYSQL_BINDIR;g
			s;@MYSQL_HOME@;$MYSQL_HOME;g
			s;@MYSQL_DATA@;$MYSQL_DATA;g
			s;@MED_USER@;$MED_USER;g
                        s;@MYSQL_LCMESSAGES_DIR@;$MYSQL_LCMESSAGES_DIR;g
			s;@MYSQL_LOGDIR@;$MYSQL_LOGDIR;g
			s;@MYSQL_BASEDIR@;$MYSQL_BASEDIR;g"  $templateFile | \
		( [ "$MYSQLD_MODE" == "REMOTE" ] && grep -v "^socket *= *" || cat ) > "$configFile"
	# ^^ Remove socket option in remote mysqld mode
}


#
# Generate configuration files from shipped templates
# and create a link to use the 
#
gen_config ()
{
	mkdir -p $MYSQL_VAR $MYSQL_CONFD $CONF 

	# Clean up old generated config. New configs have a digit as first char, so names does not match
	ls -1 $MYSQL_VAR/{my,innodb,myisam}.cnf 2>/dev/null | xargs -r rm -f

	
	# Handle if mysql host was not specified (in remote mode). Do not generate config
	if [ -z "$MYSQL_HOST" ]; then
		echo "Fatal error! MYSQL_HOST was not specified in ~/etc/virthost.sh!"
		# Clean up invalid config
		rm -f $MYSQL_VAR/*.cnf
		exit 1
	fi

	#Always generate client and common configs.
	gen_cnf_file "$MYSQL_HOME/config/0client.cnf.in" "$MYSQL_VAR/0client.cnf"
	local isNew="false";
	local isInstall="false";
	# Default storage engine is innodb
	local engine='innodb'

	#Generate main mysql config (picked up by all clients). This will include config dir.
	[ "$MYSQLD_MODE" != 'SYSTEM' ] && gen_cnf_file "$MYSQL_HOME/config/my.cnf.in" "$CONF/my.cnf"
		
	# In case of a local mysqld, check the data files if it's myisam
	if [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
		if [ -d "$MYSQL_DATA/$DBNAME" ] ; then
			# Update or restart

			if [ ! -f "$MYSQL_DATA/$DBNAME/$STUDYTBL.ibd" ] ; then
				# No InnoDB study table
				if [ -f "$MYSQL_DATA/$DBNAME/$STUDYTBL.MYD" ] ; then
					# Study table is MyISAM
					engine="myisam"
				else 
					# Neither InnoDB nor MyISAM study table exists in an existing database (not a probable scenario, but try to cover)
					local idbFiles=`find "$MYSQL_DATA/$DBNAME" -name '*ibd'`
					local mydFiles=`find "$MYSQL_DATA/$DBNAME" -name '*MYD'`

					[ -z "$ibdFiles" -a -n "$mydFiles" ] && engine="myisam"
				fi
			fi
		fi
	fi

	# Do no generate server engine specific config if thsi is a remote server
	if [ "$MYSQLD_MODE" != 'REMOTE' ];then
		# Clean up storage engine configs
		ls -1 $MYSQL_VAR/1server-*.cnf 2>/dev/null | xargs -r rm -f
		
		# Generate storage engine specific configs
		case $engine in
			myisam) gen_cnf_file "$MYSQL_HOME/config/1server-myisam.cnf.in" "$MYSQL_VAR/1server-myisam.cnf" ;;
			innodb) gen_cnf_file "$MYSQL_HOME/config/1server-innodb.cnf.in" "$MYSQL_VAR/1server-innodb.cnf" ;;
		esac

		# Generate common config
		gen_cnf_file "$MYSQL_HOME/config/2server-common.cnf.in" "$MYSQL_VAR/2server-common.cnf"
		
		( # Generate site specific config
			local ProcessMode="Process"
			[ -f "$CONF/self.rec" ] && . $CONF/self.rec
			[ "$ProcessMode" = "Database" ] && 	echo -e "[mysqld]\nlow-priority-updates" || echo -n ""
		) > "$MYSQL_VAR/3server-sitespec.cnf"
		
		# Move supported custom config file into mysql include dir
		[ -f "$CONF/mysql.cnf" -a ! -h "$CONF/mysql.cnf" ] && mv "$CONF/mysql.cnf" "$MYSQL_VAR/4custom.cnf" \
			|| touch "$MYSQL_VAR/4custom.cnf"
		[ ! -e "$CONF/mysql.cnf" ] && ln -s "$MYSQL_VAR/4custom.cnf" "$CONF/mysql.cnf"
		
	fi

	# Sync the main and drop-in configs to the place where it's picked up
	$ASROOT mycnf.asr
}

fix_scripts()
{
	FILES="bin/msql2mysql bin/mysqlaccess bin/mysqld_multi bin/mysql_config scripts/mysql_install_db bin/mysqlbug bin/mysqld_safe"

	echo -n "Process mysql scripts & config: "
	for file in $FILES;do
		if grep -q "/home/\(medsrv\|develop\)" $MYSQL_HOME/$file; then
			echo -n "."
			cat $MYSQL_HOME/$file | sed -e "s,/home/\(medsrv\|develop\),$HOME,g" > "$MYSQL_HOME/$file.tmp"
			chmod --reference="$MYSQL_HOME/$file" "$MYSQL_HOME/$file.tmp"
			[ -f "$MYSQL_HOME/$file.tmp" ] && mv -f "$MYSQL_HOME/$file.tmp" "$MYSQL_HOME/$file"
		fi
	done
	echo " Done."
}


do_stop_()
{

	# In case of a local mysqld, stop it as w did before
	if [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
		if [ ! -f $MYSQL_PID ] ; then
			echo "Component MySQL is not running"
		else
			echo "stopping MySQL ..."
			# Remove MYSQL_RUN file to indicate stop in mysqldw
			[ -f "$MYSQL_RUN" ] && rm $MYSQL_RUN
			$MYSQL_BINDIR/mysqladmin shutdown
			echo "Component MySQL stopped"
		fi
	elif [ "$MYSQLD_MODE" == 'SYSTEM' ]; then
		if $MYSQL_BINDIR/mysqladmin version > /dev/null 2>&1 ; then
			if sudo /sbin/service mysqld stop > /dev/null 2>&1;then
				echo "System MySQL stopped"
			fi
		else
			echo "System MySQL is not running"
		fi
		
	fi

} #do_stop_()


do_start_()
{
	# Check and create $MYSQL_VAR
	[ ! -d "$MYSQL_VAR" ] && mkdir -p "$MYSQL_VAR"
	[ ! -d "$ $CONF" ] && mkdir -p "$CONF"

	# Remove MYSQL_HOME/etc if its a regular directory remained from v7.0b cut
	[ -d "$MYSQL_HOME/etc" -a ! -L "$MYSQL_HOME/etc" ] && mv "$MYSQL_HOME/etc" "$TMP/old.mysql.etc"

	gen_config

	# Check for existing database and applied grants (on remote server)
	is_new_db=0
	are_grants_ok=0
	
	# Initialize mysql database if it's not remote mode.
	if [ "$MYSQLD_MODE" != 'REMOTE' ]; then
		if [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
			[ ! -d "$MYSQL_DATA" ] && mkdir -p $MYSQL_DATA >/dev/null
			if ps uxwww | grep -q -e my[i]samch -e mysq[l]d ; then
				echo "Cannot start: mysql or myisamchk is running!!!"
				exit 1
			fi
		fi
		
		if [ ! -d "$MYSQL_DATA/mysql" ]; then
			# Database init must be different, while the data files are located under medsrv home
			if [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
				fix_scripts
				$MYSQL_HOME/scripts/mysql_install_db --basedir="$MYSQL_BASEDIR" --datadir="$MYSQL_DATA" --tmpdir="$TMP" > /dev/null
			elif [ "$MYSQLD_MODE" == 'SYSTEM' ]; then
				sudo $sys_mysqlbindir/mysql_install_db --rpm --basedir="$MYSQL_BASEDIR" --datadir="$MYSQL_DATA" > /dev/null
			fi
			is_new_db=1
		fi
		if [ "$MYSQLD_MODE" == 'SYSTEM' ]; then
			sudo /bin/chown -R mysql.mysql $MYSQL_DATA || echo "$!"
			sudo /bin/chmod 2774 $MYSQL_DATA || echo "$!"
			sudo /usr/bin/gpasswd -a mysql medsrv || echo "$!"
			sudo /usr/bin/gpasswd -a medsrv mysql || echo "$!"
		fi
		
		start_daemon
		local rc=$?
		# Display different error message, with a new database and an existing one.
		if [ $is_new_db -eq 1 ]; then
			if [ $rc -ne 0 ] ; then
				echo "!!!!!!! Starting and Initializing MySQL failed"
				echo "!!!!!!! $MYSQL_DATA SHOULD BE REMOVED MANUALLY !!!!!!"
				exit 1
			fi

			# Set MySQL root password
			$MYSQL_BINDIR/mysqladmin --protocol=SOCKET --socket=$MYSQL_UNIX_PORT --user=root password "$MYSQL_ROOT_PW"
		else
			if [ $rc -ne 0 ]; then
				echo "Starting MySQL failed"
				exit 1
			fi
		fi
		
		# We consider grants OK, because locally we can apply it with root user.
		are_grants_ok=1
	else
		# Handle if mysql client data was not specified, we can't create db, apply grants
		if [ -z "$MYSQL_CLIENT" ]; then
			echo "Error! MYSQL_CLIENT was not specified in ~/etc/virthost.sh!"
			exit 1
		fi
		
		# Check server connectivity
		if ! $MYSQL_BINDIR/mysqladmin ping | grep '^mysqld is alive$'> /dev/null 2>&1; then
			echo "Error: Remote mysql server is not accessable!" >&2
		else
			# Query grants from server
			grants_tmp=$(mktemp -q)
			if ! echo "SHOW GRANTS;" | $MYSQL_BINDIR/mysql --user="$MYSQL_USER" --host="$MYSQL_HOST" > $grants_tmp 2> /dev/null ; then
				echo "Warning, can't query database privileges from '$MYSQL_HOST' for $MYSQL_USER'@'$MYSQL_CLIENT'"
				rm -f $grants_tmp
			fi
			# 
			for client in $MYSQL_CLIENT; do
				cat $grants_tmp | grep -q "^GRANT ALL PRIVILEGES ON \`$DBNAME\`\.\* TO '$MYSQL_USER'@'$client'$" && \
					cat $grants_tmp | grep -q "^GRANT ALL PRIVILEGES ON \`mysql\`\.\* TO '$MYSQL_USER'@'$client'$" && \
					are_grants_ok=1
			done
			rm -f $grants_tmp
		
			if [ $are_grants_ok -eq 1 ]; then	
				# Check if database exist
				! $MYSQL_BINDIR/mysqlshow $DBNAME > /dev/null 2>&1 && is_new_db=1
			else
				echo "Error: remote database access is not confirmed!" >&2
			fi
		fi
	fi
	if [ $is_new_db -eq 1 -o "$MYSQLD_MODE" == 'REMOTE' ];then
		# Set database privileges for mysql user
		(
			# Enable unix socket access (without user) when not REMOTE mode.
			# Always allow TCP socket access.
			for client in $MYSQL_CLIENT $( [ "$MYSQLD_MODE" != 'REMOTE' ] && echo "127.0.0.1 localhost localhost.localdomain" ); do
				echo "GRANT ALL PRIVILEGES ON $DBNAME.* TO '$MYSQL_USER'@'$client';"
				echo "GRANT ALL PRIVILEGES ON mysql.* TO '$MYSQL_USER'@'$client';"
				echo "GRANT CREATE, GRANT OPTION ON *.* TO '$MYSQL_USER'@'$client';"
				if [ "$MYSQLD_MODE" != 'REMOTE' ]; then
					echo "GRANT SHUTDOWN ON *.* to '$MYSQL_USER'@'$client';" 
				fi
			done
		) | ( 
			if [ "$MYSQLD_MODE" != 'REMOTE' ]; then
				 $MYSQL_BINDIR/mysql --user=root --host="$MYSQL_HOST" --password="$MYSQL_ROOT_PW"
			elif [ $are_grants_ok -eq 0 ]; then
				echo "You have to run following SQL commands on remote server, as root:"
				cat
				exit 1
			else
				cat > /dev/null
			fi
		)
	fi

	if [ $is_new_db -eq 1 ] ;then
		if [ "$MYSQL_ON" = "true" ]; then
			$MYSQL_BINDIR/mysqlshow $DBNAME >/dev/null 2>/dev/null
			if [ $? -ne 0 ] ; then
				echo "---- convert database --"
				$MYSQL_HOME/convert.sh > $TMP/convert.$$ 2>&1
			fi
		fi

		if [ "$MYSQLD_MODE" == 'EMBEDDED' ]; then
			# check for timezone metadata and fill if needed
			echo "select CONVERT_TZ( '2014-02-05 06:43:34', 'CET', 'SYSTEM' ) as CDT" | $MYSQL_HOME/bin/mysql | grep -q NULL
			[ $? -eq 0 ] && $MYSQL_BINDIR/mysql_tzinfo_to_sql /usr/share/zoneinfo | $MYSQL_BINDIR/mysql mysql
		fi
	fi
} #do_start_()


do_crontab_()
{
	# Get time for starting analyze table from crontabSchedule settings
	[ -f "$CONF/crontabSchedule.shi" ] && . $CONF/crontabSchedule.shi
	[ -z "$AnalyzeTableFull" ] && AnalyzeTableFull="42 04 * * *"

	cat <<- EOI
		$AnalyzeTableFull echo "ANALYZE TABLE $OBJECTTBL; ANALYZE TABLE $STUDYTBL; ANALYZE TABLE $REPORTTBL;" | $MYSQL_BINDIR/mysql $DBNAME >/dev/null  2>&1
	EOI

} #do_crontab_()



do_status_()
{
	# Mysqladmin will work on all modes
	$MYSQL_BINDIR/mysqladmin version >/dev/null 2>&1
	case $? in 
		0) echo "OK"; return 0 ;;
		1) 
			if [ -f "$MYSQL_RUN" ]; then
				echo "STOPPED"; return 1
			else
				echo "ERROR"; return 2
			fi
		;;
		*) echo "UNKNOWN"; return 127 ;;
	esac
} #do_status_()


do_beforesubmit_()
{
	do_stop_

} #do_beforesubmit_()


do_aftersubmit_()
{
	do_start_

} #do_aftersubmit_()


do_emergency_()
{
	do_stop_
	sleep 10
	do_start_

} #do_emergency_()


speedTestQueryPosix_()
{
	# param -p: get time in posix format
	time -p /home/medsrv/component/tools/sql.sh "select STYIUID from Dcstudy order by THEDATETIME limit 100;"
}

do_monitor_()
{
	/home/medsrv/component/tools/sql.sh "show variables like 'max_connections';show status where variable_name like 'Threads_connected'" -N | awk '
$1=="max_connections" {tot=$2}
$1=="Threads_connected" {cur=$2}
END {printf("mysql_proc=%1.2f\n",cur*100/tot); }

'

	if [ "$MYSQLD_MODE" != 'REMOTE' ]; then
		realTimePosix=`speedTestQueryPosix_ 2>&1 >/dev/null | tail -3 | awk ' $1 == "real" {print $2}'`
		echo "sql_query=$realTimePosix"
	fi
	exit 0
}

#
# List files/tables to be backed up grouped by categories
#
# output lines should be in '<category> <type> <names>' format
#
do_listbackup_()
{
	cat <<-EOFLISTBACKUP
		nobackup.nobackup FILE ${MYSQL_DATA#$HOME/} ${MYSQL_UNIX_PORT#$HOME/}
		config.system FILE ${MYSQL_VAR#HOME}/?custom.cnf ${MYSQL_VAR#HOME}/?server-sitespec.cnf
	EOFLISTBACKUP
}


do_capture_()
{
	if [ "$MYSQLD_MODE" != 'REMOTE' ]; then
		echo
		$MYSQL_BINDIR/mysqladmin -v processlist
	fi
}

#--- MAIN ------------------------------

check_action_ $1
if [ 0 = $? ]; then
	do_$1_ $2
else
	echo "--- Component mysql [ctrl $$]: Bad command: $1" >&2
	exit 1

fi
