docker-entrypoint.sh 2.15 KB
#!/bin/bash

MYSQL_DATA='/var/lib/mysql'
MYSQL_FILE_BEGIN="$MYSQL_DATA/MYSQL_BEGIN"

function VerifyCredintials {
  local USER=$1
  local PASSWORD=$2
  local DATABASE=$3

  if [ -z "$USER" ] || [ -z "$PASSWORD" ]; then
    echo "ERROR: MYSQL_USER and MYSQL_PASSWORD cannot be empty." > /dev/stderr
    exit -1
  fi

  if [ "$USER" = "root" ]; then
    echo "ERROR: MYSQL_USER cannot be the root account." > /dev/stderr
    exit -1
  fi

  if [ -z "$DATABASE" ]; then
    MYSQL_DATABASE="$USER"
  fi
}

function CreateInitialDatabase {
  local DATADIR=$1

#  mysql_install_db --datadir="$DATADIR" --user='mysql' --insecure --verbose
  mysqld --initialize-insecure --datadir="$DATADIR" --user="mysql"

  if [ $? -ne  0 ]; then
    echo "ERROR: Could not create an initial database." > /dev/stderr
    exit -1
  fi
}

function CreateSuperuser {
  local USER=$1
  local PASSWORD=$2

  mysql -u root --protocol=socket --wait -e "CREATE USER '$USER' IDENTIFIED BY '$PASSWORD';"
  mysql -u root --protocol=socket --wait -e "GRANT ALL PRIVILEGES ON $MYSQL_DATABASE.* TO '$USER';"
  mysql -u root --protocol=socket --wait -e "FLUSH PRIVILEGES;"
}

function CreateDatabase {
  local DATABASE=$1

  mysql -u root --protocol=socket --wait -e "CREATE DATABASE IF NOT EXISTS $DATABASE;"
}

function CreateFileBegin {
  local FILE=$1

  date +%c > $FILE
}

function StartDatabaseServer {
  mysqld $@
}

function StartDatabaseServerBackground {
  mysqld &
  sleep 5
}

function StopDatabaseServer {
  mysqladmin -u root shutdown
  sleep 5
}

function RestoreDatabase {

  mysqladmin -u root refresh

  for file in `ls /docker-entrypoint-initdb.d/*`; do
    case $file in
      *.sh )
        echo "Running '$file'..."
        . $file ;;
    esac
  done

}

function Main {

  if [ ! -f $MYSQL_FILE_BEGIN ]; then
    VerifyCredintials $MYSQL_USER $MYSQL_PASSWORD $MYSQL_DATABASE
    CreateInitialDatabase $MYSQL_DATA
    StartDatabaseServerBackground
    CreateDatabase $MYSQL_DATABASE
    CreateSuperuser $MYSQL_USER $MYSQL_PASSWORD
    RestoreDatabase
    StopDatabaseServer
    CreateFileBegin $MYSQL_FILE_BEGIN
    cat /var/log/mysqld.log
  fi

  StartDatabaseServerBackground
  tail -f /var/log/mysqld.log
}

Main $@