# http://blog.phymata.com/2017/07/29/inject-an-executable-script-into-a-container-in-kubernetes/
kind: ConfigMap
apiVersion: v1
metadata:
  name: percona-scripts
  namespace: default
data:
  entrypoint.sh: |-
    #!/bin/bash
    set -e

    if [[ -n "${DEBUG}" ]]; then
      set -x
    fi

    . /percona-scripts/functions.sh

    ipaddr=$(hostname -i | awk ' { print $1 } ')
    hostname=$(hostname)
    echo "I AM $hostname - $ipaddr"

    # if command starts with an option, prepend mysqld
    if [ "${1:0:1}" = '-' ]; then
      CMDARG="$@"
    fi

    [[ "$DEBUG" ]] && ls -lah /var/lib/mysql

    # https://github.com/paulczar/k8s-percona-xtradb-cluster/pull/1/
    [ -f /var/log/mysqld.log ] && rm /var/log/mysqld.log
    ln -s /dev/stdout /var/log/mysqld.log
    chown mysql:mysql /var/log/mysqld.log
    
    cluster_join=$(resolveip -s "${K8S_SERVICE_NAME}" || echo "")
    if [[ -z "${cluster_join}" ]]; then
      echo "I am the Primary Node"

      # http://galeracluster.com/2016/11/introducing-the-safe-to-bootstrap-feature-in-galera-cluster/
      [[ "$GALERA_UNSAFE_BOOTSTRAP" = "true" ||  "$GALERA_UNSAFE_BOOTSTRAP" = 1 ]] && enable_unsafe_bootstrap
      
      if [[ "$RESTORE_FROM_BACKUP" == "true" ]]; then
        # if test "$(ls -A "/var/lib/mysql/")"; then
        #   rm -rf /backups/mysql_backup/*
        #   mv /var/lib/mysql/* /backups/mysql_backup
        # fi
        # chown -R mysql:mysql /backups/restore/full 
        # innobackupex --copy-back /backups/restore/full 
        chown -R mysql:mysql /var/lib/mysql
        echo "restoring from backup. skipping mysql dir initialization"
      else
        init_mysql
      fi

      write_password_file
      exec mysqld --user=mysql --wsrep_cluster_name=$CLUSTER_NAME --wsrep_node_name=$hostname \
        --wsrep_cluster_address=gcomm:// --wsrep_sst_method=xtrabackup-v2 \
        --wsrep_sst_auth="xtrabackup:$XTRABACKUP_PASSWORD" \
        --wsrep_node_address="$ipaddr" $CMDARG --wsrep-provider-options="evs.version=1" --wsrep-provider-options="evs.auto_evict=30"
    else
      echo "I am not the Primary Node"
      chown -R mysql:mysql /var/lib/mysql
      write_password_file
      exec mysqld --user=mysql --wsrep_cluster_name=$CLUSTER_NAME --wsrep_node_name=$hostname \
        --wsrep_cluster_address="gcomm://$cluster_join" --wsrep_sst_method=xtrabackup-v2 \
        --wsrep_sst_auth="xtrabackup:$XTRABACKUP_PASSWORD" \
        --wsrep_node_address="$ipaddr" $CMDARG  --wsrep-provider-options=evs.version=1 --wsrep-provider-options=evs.auto_evict=30
    fi

  functions.sh: |-
    #!/bin/bash

    enable_unsafe_bootstrap() {
      if [[ -f  /var/lib/mysql/grastate.dat ]]; then
        sed -i 's/^safe_to_bootstrap:.*/safe_to_bootstrap: 1/' /var/lib/mysql/grastate.dat
      fi
    }

    disable_unsafe_bootstrap() {
      if [[ -f  /var/lib/mysql/grastate.dat ]]; then
        sed -i 's/^safe_to_bootstrap:.*/safe_to_bootstrap: 0/' /var/lib/mysql/grastate.dat
      fi
    }

    write_password_file() {
    if [[ -n "${MYSQL_ROOT_PASSWORD}" ]]; then
      cat <<EOF > /root/.my.cnf
      [client]
      user=root
      password=${MYSQL_ROOT_PASSWORD}
    EOF
    fi
    }

    init_mysql() {
    DATADIR=/var/lib/mysql
    # if we have CLUSTER_JOIN - then we do not need to perform datadir initialize
    # the data will be copied from another node
    if [ ! -e "$DATADIR/mysql" ]; then
      if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" -a -z "$MYSQL_ROOT_PASSWORD_FILE" ]; then
                          echo >&2 'error: database is uninitialized and password option is not specified '
                          echo >&2 '  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ROOT_PASSWORD_FILE,  MYSQL_ALLOW_EMPTY_PASSWORD or MYSQL_RANDOM_ROOT_PASSWORD'
                          exit 1
                  fi

      if [ ! -z "$MYSQL_ROOT_PASSWORD_FILE" -a -z "$MYSQL_ROOT_PASSWORD" ]; then
        MYSQL_ROOT_PASSWORD=$(cat $MYSQL_ROOT_PASSWORD_FILE)
      fi
      mkdir -p "$DATADIR"

      echo "Running --initialize-insecure on $DATADIR"
      ls -lah $DATADIR
      # https://dev.mysql.com/doc/refman/5.7/en/data-directory-initialization-mysqld.html
      mysqld --initialize-insecure
      chown -R mysql:mysql "$DATADIR"
      chown mysql:mysql /var/log/mysqld.log
      echo 'Finished --initialize-insecure'

      mysqld --user=mysql --datadir="$DATADIR" --skip-networking &
      pid="$!"

      mysql=( mysql --protocol=socket -uroot )

      for i in {30..0}; do
        if echo 'SELECT 1' | "${mysql[@]}" &> /dev/null; then
          break
        fi
        echo 'MySQL init process in progress...'
        sleep 1
      done
      if [ "$i" = 0 ]; then
        echo >&2 'MySQL init process failed.'
        exit 1
      fi

      # sed is for https://bugs.mysql.com/bug.php?id=20545
      mysql_tzinfo_to_sql /usr/share/zoneinfo | sed 's/Local time zone must be set--see zic manual page/FCTY/' | "${mysql[@]}" mysql
      if [ ! -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
        MYSQL_ROOT_PASSWORD="$(pwmake 128)"
        echo "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD"
      fi
      "${mysql[@]}" <<-EOSQL
        -- What's done in this file shouldn't be replicated
        --  or products like mysql-fabric won't work
        SET @@SESSION.SQL_LOG_BIN=0;
        CREATE USER 'root'@'%' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
        GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION ;
        ALTER USER 'root'@'localhost' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}';
        CREATE USER 'xtrabackup'@'localhost' IDENTIFIED BY '$XTRABACKUP_PASSWORD';
        GRANT RELOAD,PROCESS,LOCK TABLES,REPLICATION CLIENT ON *.* TO 'xtrabackup'@'localhost';
        GRANT REPLICATION CLIENT ON *.* TO monitor@'%' IDENTIFIED BY 'monitor';
        GRANT PROCESS ON *.* TO monitor@localhost IDENTIFIED BY 'monitor';
        DROP DATABASE IF EXISTS test ;

        CREATE USER 'backup'@'%' IDENTIFIED BY '$XTRABACKUP_PASSWORD';
        GRANT CREATE, SELECT, CREATE TABLESPACE, RELOAD, PROCESS, SUPER, LOCK TABLES, REPLICATION CLIENT ON *.* TO 'backup'@'%';
        CREATE DATABASE IF NOT EXISTS PERCONA_SCHEMA;
        GRANT ALL ON PERCONA_SCHEMA.* TO 'backup'@'%';

        FLUSH PRIVILEGES ;
    EOSQL
      if [ ! -z "$MYSQL_ROOT_PASSWORD" ]; then
        mysql+=( -p"${MYSQL_ROOT_PASSWORD}" )
      fi

      if [ "$MYSQL_DATABASE" ]; then
        echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" | "${mysql[@]}"
        mysql+=( "$MYSQL_DATABASE" )
      fi

      if [ "$MYSQL_USER" -a "$MYSQL_PASSWORD" ]; then
        echo "CREATE USER '"$MYSQL_USER"'@'%' IDENTIFIED BY '"$MYSQL_PASSWORD"' ;" | "${mysql[@]}"

        if [ "$MYSQL_DATABASE" ]; then
          echo "GRANT ALL ON \`"$MYSQL_DATABASE"\`.* TO '"$MYSQL_USER"'@'%' ;" | "${mysql[@]}"
        fi

        echo 'FLUSH PRIVILEGES ;' | "${mysql[@]}"
      fi

    #   if [ ! -z "$MYSQL_ONETIME_PASSWORD" ]; then
    #     "${mysql[@]}" <<-EOSQL
    #       ALTER USER 'root'@'%' PASSWORD EXPIRE;
    # EOSQL
    #  fi
      if ! kill -s TERM "$pid" || ! wait "$pid"; then
        echo >&2 'MySQL init process failed.'
        exit 1
      fi

      echo
      echo 'MySQL init process done. Ready for start up.'
      echo
      #mv /etc/my.cnf $DATADIR
    fi

    }
