# bin/bash
set -x
set -v

ulimit -c unlimited
ulimit -n $(( 32 * 1024 ))
MS=${1:-master}

MASTER_PORT=3310

if [ -d /dev/shm ];
then
   SHM=/dev/shm
else
   SHM=/run/shm
fi

if [ $MS == "master" ]; then
   EXTRA_OPTS=--log-bin=${SHM}/oltp_master/mysqlbin
   SERVER_ID=120
   PORT=${MASTER_PORT}
else
   MS=slave
   EXTRA_OPTS=--slave-parallel-workers=160
   SERVER_ID=180
   PORT=3320
fi

DIR=${SHM}/oltp_${MS}
mkdir -p ${DIR}
cd /usr/local/mysql
( scripts/mysql_install_db --no-defaults --datadir=${DIR} ${EXTRA_OPTS} --socket /tmp/oltp_${MS}.sock --verbose --force
bin/mysqld --no-defaults \
    --pid-file=/tmp/${MS}.pid \
    --port ${PORT} --datadir=${DIR} --socket /tmp/oltp_${MS}.sock ${EXTRA_OPTS} --server-id=${SERVER_ID} \
    --innodb_log_file_size=200M --innodb_log_files_in_group=5 \
    --innodb-buffer-pool-size=6G --innodb-buffer-pool-instances=6 \
    --innodb_file_per_table --binlog_checksum=NONE --innodb_checksum_algorithm=none  \
    --max-connections=16000 --max_prepared_stmt_count=1M \
    --core-file \
    2>&1 | tee -a /tmp/${MS}.log ) &


# wait for startup
while [ 1 ]; do
  mysql -S /tmp/oltp_${MS}.sock -u root -e 'show databases' && break
  sleep 0.5
done

# will only work once before the password is set
cat << EOF | mysql -S /tmp/oltp_${MS}.sock -u root


grant replication slave  on *.* to 'repl'@'localhost' identified by 'repl'; 
SET PASSWORD = PASSWORD('mysql');
INSTALL PLUGIN rpl_semi_sync_${MS} SONAME 'semisync_${MS}.so';

SET GLOBAL rpl_semi_sync_${MS}_enabled = 1;
delete from mysql.user where user='' or host not in ('localhost', '127.0.0.1');
flush logs;
select user,host from mysql.user;
show ${MS} status;

EOF

if [ $MS == "slave" ]; then

cat << EOF1 | mysql -S /tmp/oltp_${MS}.sock -u root -pmysql

change master to master_host='localhost', master_port=3310, master_user='repl',master_password='repl', master_log_file='mysqlbin.000004', master_log_pos=0;
start slave;

EOF1

fi


