#!/bin/bash
#
# $Id: post-mysql-install 3661 2013-06-25 22:04:33Z dhill $
#
# Post-install steps for calpont-mysql install

# check log for error
checkForError() {
	# check for password error
	grep "ERROR 1045" ${tmpdir}/mysql_install.log > ${tmpdir}/error.check
	if [ `cat ${tmpdir}/error.check | wc -c` -ne 0 ]; then
		  echo "MySQL Password file missing or incorrect, check .my.cnf file"
		  rm -f ${tmpdir}/error.check
          # Test we are using systemd
          systemctl cat mariadb.service > /dev/null 2>&1
          if [ $? -eq 0 ]; then
              systemctl stop mariadb.service > /dev/null 2>&1
          else
              pkill mysqld
          fi
		  sleep 2
		  exit 2;
	fi

	rm -f ${tmpdir}/error.check

        #---------------------------------------------------------------------------
        # See if engine columnstore exist
        #---------------------------------------------------------------------------
        echo "checking for engine columnstore..."
        mysql \
                --user=root \
                --execute='show engines;' \
                | grep -i columnstore

        #
        # Add compressiontype column to SYSCOLUMN if applicable
        #
        if [ $? -ne 0 ]; then
                echo "columnstore doesn't exist"
                exit 1
        fi

        echo "columnstore exist"

	return 0;
}

rpmmode=install
tmpdir="/tmp"

for arg in "$@"; do
	if [ $(expr -- "$arg" : '--rpmmode=') -eq 10 ]; then
		rpmmode="$(echo $arg | awk -F= '{print $2}')"
	elif [ $(expr -- "$arg" : '--tmpdir=') -eq 9 ]; then
		tmpdir="$(echo $arg | awk -F= '{print $2}')"
	else
		echo "ignoring unknown argument: $arg" 1>&2
	fi
done

# Restart in the same way that mysqld will be started normally.
# Test we are using systemd
systemctl cat mariadb.service > /dev/null 2>&1
if [ $? -eq 0 ]; then
    systemctl stop mariadb.service > /dev/null 2>&1
else
    pkill mysqld
fi
sleep 2
export MYSQL_OPTS="--skip-grant-tables"
# Test we are using systemd
systemctl cat mariadb.service > /dev/null 2>&1
if [ $? -eq 0 ]; then
    systemctl start mariadb.service
else
    /usr/bin/mysqld_safe --skip-grant-tables &
fi
unset MYSQL_OPTS

sleep 5

# Install various Calpont stuff...
install_mcs_mysql.sh  --tmpdir=$tmpdir
checkForError
if [ $? -ne 0 ]; then
    echo "ERROR: Invalid password in .my.cnf, or Columnstore plugin install missing"
    # Test we are using systemd
    systemctl cat mariadb.service > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        systemctl stop mariadb.service > /dev/null 2>&1
    else
        pkill mysqld
    fi
    sleep 2
    exit 2;
fi

# Test we are using systemd
systemctl cat mariadb.service > /dev/null 2>&1
if [ $? -eq 0 ]; then
    systemctl stop mariadb.service > /dev/null 2>&1
else
    pkill mysqld
fi


exit 0

