#!/bin/bash
########################################################################
# Note: This should be executed by root before tomcat is started.
#       The MySql instance needs to be running.
########################################################################
function usage {
echo "
Usage: ${PGM}

Performs the following on the MySql instance for a Gratia Service
  1. Verifies MySql is installed
  2. Verifies the mysqld daemon is running  
  3. Verifies that the port specified in the Gratia configuration file
     matches that set in the MySql /etc/my.cnf file.
     Note: this not comprehensive if they really have different ports
           for mysqld and the clients.
  4. Checks to see if an existing MySql instance has the root password
     set and verifies against the Gratia authorization properties file.
     If root password is not set and the Gratia Authorization specifies
     it, root passowrd will be set.
  5. Creates the mysql gratia database
  6. Sets privileges for Gratia users
"
########################################################################
}
#-------------------------------
function ask_continue {
  while :
  do
    echo -n "... do you want to continue? y/n: "
    read ans
    case "$ans" in
     "y" ) echo ; return ;;
     "n" ) echo "... terminating at your request";exit 1 ;;
      *  ) continue ;;
    esac
  done
}
#-------------------------------
function verify_mysql_installed {
  echo "... validating MySql is installed"
  if [ ! -e "$MYSQL_CONFIG" ];then
    echo "ERROR: Could not complete Gratia configuration"
    echo "Cannot find $MYSQL_CONFIG"
    echo "You must install and configure MySQL 5 before configuring Gratia."
    exit 1
  fi
  if [ ! -e "/etc/init.d/mysqld" ];then
    echo "ERROR: Could not find initd service: /etc/init.d/mysqld"
    echo "Did you install of MySql work correctly?"
    exit 1
  fi
}
#-------------------------------
function validate_mysql_config {
  verify_mysql_installed
  echo "... validating MySql port being used"
  mysql_cnf_port="`egrep -v '^#' $MYSQL_CONFIG | grep port | sed -e's/=/ /' | awk '{print $2}' | sort -u `"
  [ "x$mysql_cnf_port" = "x" ] && mysql_cnf_port=$DEFAULT_MYSQL_PORT
  if [ "$DBPORT" != "$mysql_cnf_port" ];then
    echo "ERROR: The MySql port specified in the Gratia configuration file does not"
    echo "match the port specified in the mysql configuration file."
    echo "  File: $CONFIGURATIONS"
    echo "  Attribute: `grep ^service.mysql.url $CONFIGURATIONS`"
    echo "  MySql: $MYSQL_CONFIG"
    echo "  Attribute: `egrep -v '^#' $MYSQL_CONFIG | grep port`"
    echo "Please correct."
    exit 1
  fi
  echo "... port: $DBPORT"
}
#-------------------------------
function verify_mysql_running {
  echo "... verifying mysqld daemon is running"
  cmd="service mysqld status"
  echo "$cmd"
  $cmd;rtn=$?
  if [ "$rtn" != "0" ];then
    echo "ERROR: The MySql mysqld daemon does not appear to be running"
    echo "You will need it running to complete this installation."
    exit 1
  fi
}
#-------------------------------
function check_if_root_passwd_set {
  # Attempts to determine if the root password has been set already
  echo "quit" | mysql -B --unbuffered  --user=root --port=$DBPORT &>/dev/null;rtn=$?
  if [ "$rtn" = "0" ];then
    ROOT_SET=0 
    echo "... root password has not been set yet."
  else
    ROOT_SET=1
    echo "... root password has already been set."
  fi
}
#-------------------------------
function mysql_arguments {
  # If the root password is already set, then a tmp file is needed
  # so as not to show the password in the mysql execution.
  local passwd_arg=""
  if [ "$ROOT_SET" = "1" ];then 
    passwd_arg=" --defaults-extra-file=$TMPPSWD "
    create_tmp_passwd_file
  fi
  echo "$passwd_arg -B --unbuffered  --user=root --port=$DBPORT" 
}
#-------------------------------
function verify_root_pswd {
  # If the root password is already set, then we are verifying the one
  # in the Gratia authorization file is correct.
  [ "$ROOT_SET" = "0" ] && return
  echo "... verifying if root password is correct"
  echo "quit" | mysql `mysql_arguments` &>/dev/null;rtn=$?
  rm -f $TMPPSWD
  if [ "$rtn" != "0" ];then 
    echo "The root mysql password has already been set and the one specified in the "
    echo "Gratia authorization file does not match:"
    echo "  File: $AUTHORIZATIONS"
    echo "  Attribute: service.mysql.rootpassword"
    echo "Please correct."
    exit 1 
  fi
}
#-------------------------------
function create_tmp_passwd_file {
  cat >$TMPPSWD <<EOF
[client]
password="${DBROOTPASSWD}"
EOF
  chmod 600 $TMPPSWD
}
#----------------------------------
function get_mysql_attributes {
  DBPORT=`grep ^service.mysql.url $CONFIGURATIONS | tr ':' ' ' | tr '/' ' ' | awk '{print $4;}'`
  DBNAME=`grep ^service.mysql.url $CONFIGURATIONS | tr ':' ' ' | tr '/' ' ' | awk '{print $NF;}'`
  DBHOST=`grep ^service.mysql.url $CONFIGURATIONS | tr ':' ' ' | tr '/' ' ' | awk '{print $3;}'`

  DBUSER=`grep           ^service.mysql.user         $AUTHORIZATIONS | tr '=' ' ' | awk '{print $NF;}'`
  DBPASSWD=`grep         ^service.mysql.password     $AUTHORIZATIONS | tr '=' ' ' | awk '{print $NF;}'`
  DBREADER=`grep         ^service.reporting.user     $AUTHORIZATIONS | tr '=' ' ' | awk '{print $NF;}'`
  DBREADERPASSWD=`grep   ^service.reporting.password $AUTHORIZATIONS | tr '=' ' ' | awk '{print $NF;}'`
  DBROOTPASSWD=`grep     ^service.mysql.rootpassword $AUTHORIZATIONS | tr '=' ' ' | awk '{print $NF;}'`
}
#-------------------------------
function create_gratia_sql_updates_file {
  > $TMPSQL
  #-- create the root password is needed --
  if [ "$ROOT_SET" = "0" ];then 
    echo "... creating the root password specified" 
    if [ "x$DBROOTPASSWD" = "x" ] || [ $DBROOTPASSWD = "service.mysql.rootpassword" ];then
      DBROOTPASSWD=""
    fi
    cat >$TMPSQL <<EOF
use mysql;
UPDATE user SET PASSWORD=PASSWORD("$DBROOTPASSWD") WHERE User = 'root';
FLUSH PRIVILEGES;
EOF
  fi
  #-- create database and set privileges --
  echo "... creating $DBNAME database and updating privileges"
  [ $DBHOST == "localhost" ] && host=`hostname -f` || host=$DBHOST
  cat >>$TMPSQL <<EOF
CREATE database $DBNAME;
GRANT ALL PRIVILEGES ON $DBNAME.* TO '$DBUSER'@'localhost'   IDENTIFIED BY '$DBPASSWD';
GRANT ALL PRIVILEGES ON $DBNAME.* TO '$DBUSER'@'$host'       IDENTIFIED BY '$DBPASSWD';
GRANT SELECT,EXECUTE ON $DBNAME.* TO '$DBREADER'@'localhost' IDENTIFIED BY '$DBREADERPASSWD';
GRANT SELECT,EXECUTE ON $DBNAME.* TO '$DBREADER'@'$host'     IDENTIFIED BY '$DBREADERPASSWD';
GRANT ALL PRIVILEGES ON $DBNAME.* TO 'root'@'$DBHOST'        IDENTIFIED BY '$DBROOTPASSWD';
GRANT ALL PRIVILEGES ON $DBNAME.* TO 'root'@'localhost'      IDENTIFIED BY '$DBROOTPASSWD';
EOF
  chmod 600 $TMPSQL
}
#----------------------------
function update_mysql {
  cat $TMPSQL | mysql `mysql_arguments`;rtn=$?
  rm -f $TMPSQL $TMPPSWD
  if [ "$rtn" != "0" ];then
    echo "ERROR: The attempt to create/update the Gratia database failed."
    exit 1
  fi
}
### MAIN ######################################################
#set -x
PGM=`basename $0`
CONFIGURATIONS=/etc/gratia/services/service-configuration.properties
AUTHORIZATIONS=/etc/gratia/services/service-authorization.properties
TMPPSWD=/tmp/.${PGM}.pwsd.$$   # very temporary passwd file
TMPSQL=/tmp/.${PGM}.sql.$$     # very temporary sql file
MYSQL_CONFIG=/etc/my.cnf
DEFAULT_MYSQL_PORT=3306

case $1 in
 "?" | "-?" | "-h" | "-help" | "--help" ) usage;exit 1;;
  * ) ;;
esac

echo "
Creating Gratia database based on the properties you updated in these files:
  $CONFIGURATIONS
  $AUTHORIZATIONS"

verify_mysql_installed 
verify_mysql_running 
get_mysql_attributes
validate_mysql_config
check_if_root_passwd_set  # ROOT_SET=1 - password set / ROOT_SET=0 - pswd not set
verify_root_pswd 
create_gratia_sql_updates_file 
update_mysql 

echo "
Gratia database installation complete.
"

exit 

