#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2015, 2016 Synacor, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software Foundation,
# version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
# ***** END LICENSE BLOCK *****
# 

if [ x`whoami` != "xzimbra" ]; then
  echo "Error: must be run as user zimbra"
  exit 1
fi

usage() {
  echo "$0 [--help] [--sql_root_pw <password>] [--mysql_memory_percent 30]"
  echo "  --sql_root_pw defaults to random password if not specified."
  echo "  --mysql_memory_percent defaults to 30 percent if not specified."
}

source /opt/zimbra/bin/zmshutil || exit 1
zmsetvars -f

#
# Sanity checks
#
zmassert -x /opt/zimbra/libexec/zmmycnf
zmassert -x /opt/zimbra/bin/mysqladmin
zmassert -x /opt/zimbra/bin/mysql
zmassert -x /opt/zimbra/bin/zmlocalconfig
zmassert -x /opt/zimbra/bin/zmmypasswd
zmassert -x /opt/zimbra/common/share/mysql/scripts/mysql_install_db
zmassert -r ${zimbra_db_directory}/db.sql
zmassert -r ${zimbra_db_directory}/versions-init.sql

for opt in "$@"; do
  case "$opt" in
    -help|--help|-h|--help)
      usage
      exit 0
      shift
      ;;
    -verbose|--verbose|-v|--v)
      verbose=yes
      shift
      ;;
    --sql_root_pw)
      shift
      sql_root_pw=$1
      shift
      ;;
    --mysql_memory_percent)
      shift
      mysql_memory_percent=$1
      shift
      ;;
    --*|-*)
      echo "Unknown option $opt"
      usage
      exit 1
      shift
      ;;
  esac
done

mysql_memory_percent=${mysql_memory_percent:=30}
if [ x"$verbose" = "xyes" ]; then
  echo "mysql_memory_percent=$mysql_memory_percent"
fi

#
# Create necessary directories
#
echo '*' Creating required directories
mkdir -p ${mysql_data_directory}
mkdir -p ${zimbra_index_directory}
mkdir -p ${zimbra_store_directory}
mkdir -p ${zimbra_log_directory}

#
# Generate a mysql config file
#
echo '*' Generating mysql config ${mysql_mycnf}
rm -f ${mysql_mycnf}
/opt/zimbra/libexec/zmmycnf --innodb-buffer-pool-memory-percent \
  $mysql_memory_percent > ${mysql_mycnf}

#
# Create database
#
echo '*' Creating database in ${mysql_data_directory}
(/opt/zimbra/common/share/mysql/scripts/mysql_install_db \
    --basedir=/opt/zimbra/common \
    --defaults-file=${mysql_mycnf}) \
    >> ${zimbra_log_directory}/zmmyinit.log 2>&1

#
# Start mysql server
#
echo '*' Starting mysql server
/opt/zimbra/bin/mysql.server start \
    >> ${zimbra_log_directory}/zmmyinit.log 2>&1

# make sure we can connect before continuing 
until `echo "show processlist" | /opt/zimbra/bin/mysql -u root --password= > /dev/null 2>&1`; do
  let i++
  sleep 5
  if [ $i -gt 25 ]; then
    echo '*' Failed to connect to mysql...giving up!
    exit -1
  else 
    echo '*' Failed to connect to mysql...retrying
  fi
done

#
# Load zimbra sql files
#
echo '*' Loading schema ${zimbra_db_directory}/db.sql 
/opt/zimbra/bin/mysql -u root --password= < \
    ${zimbra_db_directory}/db.sql

if [ -f "${zimbra_db_directory}/create_sharing_database.sql" ];then
  echo '*' Loading schema ${zimbra_db_directory}/create_sharing_database.sql 
  /opt/zimbra/bin/mysql -u root --password= < \
      ${zimbra_db_directory}/create_sharing_database.sql
fi

echo '*' Loading version from ${zimbra_db_directory}/versions-init.sql
/opt/zimbra/bin/mysql -u root --password= < \
    ${zimbra_db_directory}/versions-init.sql

if [ -f "${zimbra_db_directory}/backup-version-init.sql" ]; then
  echo '*' Loading version from ${zimbra_db_directory}/backup-version-init.sql
  /opt/zimbra/bin/mysql -u root --password= < \
    ${zimbra_db_directory}/backup-version-init.sql
fi

#
# Delete wildcard user login entries
#
/opt/zimbra/bin/mysql -u root --password= -e "DROP USER ''@'localhost'; DROP USER ''@'`hostname`';"

#
# Generate passwords for mysql into local config
#
if [ x$sql_root_pw = "x" ]; then
    echo '*' Setting random passwd for mysql root user in zimbra localconfig
    /opt/zimbra/bin/zmlocalconfig -r -f -e mysql_root_password
    
    echo '*' Setting random passwd for mysql zimbra user in zimbra localconfig
    /opt/zimbra/bin/zmlocalconfig -r -f -e zimbra_mysql_password
else
    echo '*' Setting passwd for mysql root user in zimbra localconfig
    /opt/zimbra/bin/zmlocalconfig -f -e mysql_root_password=$sql_root_pw
    echo '*' Setting passwd for mysql zimbra user in zimbra localconfig
    /opt/zimbra/bin/zmlocalconfig -f -e zimbra_mysql_password=$sql_root_pw
fi

#
# Change mysql root user password, but first read back the passwords 
# zimbra local config - they was generated above.  Note that we can not
# use 'zmmypasswd --root' here because of bootstrapping problems - at
# this stage we know that the root password is empty.
#
zmsetvars -f
echo '*' Changing mysql root user password
cat <<EOF | /opt/zimbra/bin/mysql -u root --password=
    SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${mysql_root_password}');
    SET PASSWORD FOR 'root'@'`hostname`' = PASSWORD('${mysql_root_password}');
    SET PASSWORD FOR 'root'@'127.0.0.1' = PASSWORD('${mysql_root_password}');
    SET PASSWORD FOR 'root'@'::1' = PASSWORD('${mysql_root_password}');
    SET PASSWORD FOR 'root'@'localhost.localdomain' = PASSWORD('${mysql_root_password}');
EOF

echo '*' Changing mysql zimbra user password
/opt/zimbra/bin/zmmypasswd ${zimbra_mysql_password}
