apiVersion: v1
kind: ConfigMap
metadata:
  name: mysql
  labels:
    app: mysql
data:
  master-master.cnf: |
    # Apply this config only on the group replication in multi-master.
    [mysqld]
    gtid_mode=ON
    enforce_gtid_consistency=ON
    master_info_repository=TABLE
    relay_log_info_repository=TABLE
    binlog_checksum=NONE
    log_slave_updates=ON
    log_bin=binlog
    binlog_format=ROW
    transaction_write_set_extraction=XXHASH64
    loose-group_replication_group_name="aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
    loose-group_replication_start_on_boot=OFF
    loose-group_replication_bootstrap_group=OFF
    loose-group_replication_ip_whitelist=10.0.0.0/8
    loose-group_replication_single_primary_mode=OFF
    event_scheduler=OFF
  int-mysql.sh: |
    #!/bin/bash
    set -ex
    # Generate mysql server-id from pod ordinal index.
    [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
    ordinal=${BASH_REMATCH[1]}
    echo [mysqld] > /mnt/conf.d/server-id.cnf
    # Add an offset to avoid reserved server-id=0 value.
    echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
    # Copy appropriate conf.d files from config-map to emptyDir.
    cp /mnt/config-map/master-master.cnf /mnt/conf.d/
    echo "loose-group_replication_local_address=mysql-$ordinal.mysql:24901" >> /mnt/conf.d/master-master.cnf
    echo "loose-group_replication_group_seeds=mysql-0.mysql:24901,mysql-1.mysql:24901,mysql-2.mysql:24901" >> /mnt/conf.d/master-master.cnf
    echo "report_host=mysql-$ordinal.mysql" >> /mnt/conf.d/master-master.cnf
    if [[ $ordinal -ne 0 ]]; then
      echo "super_read_only=ON" >> /mnt/conf.d/master-master.cnf
    fi
  clone-mysql.sh: |
    #!/bin/bash
    set -ex
    # Skip the clone if data already exists.
    # TODO: think of something like: if data older than 24h- overwrit it!
    [[ -d /var/lib/mysql/mysql ]] && exit 0
    # Skip the clone on master (ordinal index 0).
    [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
    ordinal=${BASH_REMATCH[1]}
    [[ $ordinal -eq 0 ]] && exit 0
    # Add support to crashed master
    # Clone data from previous peer.
    ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
    # Prepare the backup.
    xtrabackup --prepare --target-dir=/var/lib/mysql
    date +%s > /var/lib/mysql/timestamp
    rm -rf /var/lib/mysql/auto.cnf
  xtrabackup.sh: |
    #!/bin/bash
    set -ex
    # Generate mysql server-id from pod ordinal index.
    [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
    ordinal=${BASH_REMATCH[1]}
    echo "Waiting for mysqld to be ready (accepting connections)"
    until mysql -h mysql-$ordinal.mysql -e "SELECT 1"; do sleep 1; done
    if [[ $ordinal -eq 0 && ! -f /var/lib/mysql/configured ]]; then
      bash /mnt/config-map/config.sh
      date > /var/lib/mysql/configured
    fi
    # Mysql-0 need always be bootstraped if there are no others nodes
    # TODO: 1) handle scale down to 0 situation - mysql-0 need to by bootstraped after scale up
    # TODO: 2) handle mysql-0 crash - no need for bootstrap
    replication_group_members=`mysql -h mysql-rw -sNe \
     "SELECT count(*) FROM performance_schema.replication_group_members WHERE MEMBER_STATE='ONLINE'" || echo 0`
    if [[ $ordinal -eq 0 && $replication_group_members -eq 0 ]]; then
    # This handle TODO 1) and 2)
      bash /mnt/config-map/bootstrap-repl.sh
      date > /var/lib/mysql/bootstraped
    else
    # If data are copied by xtrabackup, set @@GLOBAL.GTID_PURGED and start replication
       cd /var/lib/mysql
       bash /mnt/config-map/repl.sh
    fi
    cd /var/lib/mysql
    # Start a server to send backups when requested by peers.
    exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
      "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root"
  config.sh: |
    #!/bin/bash
    set -ex
    mysql -h 127.0.0.1 -e "SET SQL_LOG_BIN=OFF"
    mysql -h 127.0.0.1 -e "CREATE USER rpl_user@'%' IDENTIFIED BY 'password'"
    mysql -h 127.0.0.1 -e "GRANT REPLICATION SLAVE ON *.* TO rpl_user@'%'"
    mysql -h 127.0.0.1 -e "FLUSH PRIVILEGES"
    mysql -h 127.0.0.1 -e "CHANGE MASTER TO MASTER_USER='rpl_user', MASTER_PASSWORD='password' FOR CHANNEL 'group_replication_recovery'"
    mysql -h 127.0.0.1 -e "INSTALL PLUGIN group_replication SONAME 'group_replication.so'"
  repl.sh: |
    #!/bin/bash
    set -ex
    cd /var/lib/mysql
    if [[ -f xtrabackup_binlog_info ]]; then
      [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
      ordinal=${BASH_REMATCH[1]}
      [[ `cat xtrabackup_binlog_info | tr -d  '\n'` =~ ^(.*?)[[:space:]]+(.*?)[[:space:]]+(.*?)$ ]] || exit 1
      mv xtrabackup_binlog_info xtrabackup_binlog_info.bck
      mysql -h 127.0.0.1 -e "SET global event_scheduler=OFF"
      mysql -h 127.0.0.1 -e "SET SQL_LOG_BIN=OFF"
      mysql -h 127.0.0.1 -e "RESET MASTER"
      mysql -h 127.0.0.1 -e "RESET SLAVE ALL"
      mysql -h 127.0.0.1 -e "SET @@GLOBAL.GTID_PURGED='${BASH_REMATCH[3]}'"
      mysql -h 127.0.0.1 -e "CHANGE MASTER TO MASTER_USER='rpl_user', MASTER_PASSWORD='password' FOR CHANNEL 'group_replication_recovery'"
      mysql -h 127.0.0.1 -e "SET SQL_LOG_BIN=ON"
      mysql -h 127.0.0.1 -e "START GROUP_REPLICATION"
      mysql -h 127.0.0.1 -e "SET global event_scheduler=ON"
    else
      mysql -h 127.0.0.1 -e "START GROUP_REPLICATION"
    fi
  bootstrap-repl.sh: |
    #!/bin/bash
    set -ex
    mysql -h 127.0.0.1 -e "SET GLOBAL group_replication_bootstrap_group=ON"
    mysql -h 127.0.0.1 -e "START GROUP_REPLICATION"
    mysql -h 127.0.0.1 -e "SET GLOBAL group_replication_bootstrap_group=OFF"
    mysql -h 127.0.0.1 -e "SET global event_scheduler=ON"
    mysql -h 127.0.0.1 -e "SET SQL_LOG_BIN=ON"
  data1.sql: |
    CREATE DATABASE test;
    USE test;
    CREATE TABLE t1 (c1 INT PRIMARY KEY, c2 TEXT NOT NULL);
    INSERT INTO t1 VALUES (1, 'Luis');
  data2.sql: |
    INSERT INTO test.t1 VALUES (2, 'Krol');
  data3.sql: |
    INSERT INTO test.t1 VALUES (3, 'Psy');
  readiness.sh: |
    #!/bin/bash
    set -ex
    mysql -sN -h 127.0.0.1 -e "SELECT * FROM performance_schema.replication_group_members WHERE MEMBER_HOST LIKE '$HOSTNAME.mysql%' AND MEMBER_STATE='ONLINE'" | grep $HOSTNAME.mysql
