#!/usr/bin/env bash

sshPort=$1
mgIP=$2
sqlPwd=$3
kind=$4

init_env() {
  if ! ping -c 1 -w 15 itityunwei.cn &> /dev/null;then
    echo "Network Connect Failed. Please Check";
    exit 127
  fi

  setenforce 0 && \
  sed -ri 's/^(SELINUX=.*)/SELINUX=disabled/' /etc/selinux/config
  systemctl enable --now firewalld
  firewall-cmd --permanent --remove-service="ssh"
  firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=154.207.252.0/24 port port=${sshPort} protocol=tcp accept"
  firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=103.232.214.0/24 port port=${sshPort} protocol=tcp accept"
  firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=${mgIP} port port=6033 protocol=tcp accept"
  if [ "${kind}" == "master" ]; then
    slaveNet=$5
    if [ "${slaveNet}" != "" ]; then
      firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=${slaveNet} port port=6033 protocol=tcp accept"
    fi
  fi
  firewall-cmd --reload

  yum install -y chrony
  systemctl restart chronyd && systemctl enable chronyd
  chronyc tracking && chronyc -a makestep
}

install_mysql() {
  # clean old env
  systemctl stop mysqld mariadb &>/dev/null
  yum erase -y  `rpm -qa | egrep "mariadb|mysql"` 2> /dev/null
  rm -rvf /etc/my.cnf /var/lib/mysql /var/log/mysqld.log
  userdel -rf mysql &>/dev/null
  groupdel -rf mysql &>/dev/null


  # install
  yum install -y  perl-Data-Dumper expect
  mkdir /usr/local/src/mysql
  cd /usr/local/src/mysql
  if [ ! -f "/usr/local/src/mysql/MySQL-client-5.6.51-1.el7.x86_64.rpm" ]; then
    wget http://itityunwei.cn/opsctl/package/MySQL-client-5.6.51-1.el7.x86_64.rpm
  fi
  if [ ! -f "/usr/local/src/mysql/MySQL-server-5.6.51-1.el7.x86_64.rpm" ]; then
    wget http://itityunwei.cn/opsctl/package/MySQL-server-5.6.51-1.el7.x86_64.rpm
  fi

  if ! yum localinstall -y *; then
    echo "[ERROR]:MySQL Failed Installed,Please check manually";
    exit 1
  fi

  if [ "${kind}" == "master" ]; then
      echo "[mysqld]
server-id=100
port=6033
innodb_rollback_on_timeout=1
innodb_lock_wait_timeout=600
max_connections=1750
log-bin=mysql-bin
binlog-format = 'ROW'
bind-address = 0.0.0.0
datadir=/var/lib/mysql" > /etc/my.cnf
  else
      echo "[mysqld]
server-id=101
port=6033
innodb_rollback_on_timeout=1
innodb_lock_wait_timeout=600
max_connections=1750
log-bin=mysql-bin
binlog-format = 'ROW'
bind-address = 0.0.0.0
datadir=/var/lib/mysql" > /etc/my.cnf
  fi

  #start
  echo "[Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html
After=network.target
After=syslog.target

[Install]
WantedBy=multi-user.target

[Service]
User=mysql
Group=mysql
ExecStart=`which mysqld` --defaults-file=/etc/my.cnf
LimitNOFILE = 5000
#Restart=on-failure
#RestartPreventExitStatus=1
#PrivateTmp=false" > /usr/lib/systemd/system/mysqld.service
  systemctl daemon-reload
  systemctl enable --now mysqld
  sleep 10;

  ranPwd=$(awk -F": " '/password/{print $2}' /root/.mysql_secret)
  `which expect` <<EOF
set timeout -1;
spawn mysql_secure_installation;
expect "*:*"
send "${ranPwd}\r"
expect "*Y/n*"
send "Y\r"
expect "*password:*"
send "${sqlPwd}\r"
expect "*password:*"
send "${sqlPwd}\r"
expect "*Y/n*"
send "Y\r"
expect "*Y/n*"
send "Y\r"
expect "*Y/n*"
send "Y\r"
expect "*Y/n*"
send "Y\r"
expect eof
EOF
  mysql -uroot -p${sqlPwd} -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '${sqlPwd}' WITH GRANT OPTION;"
  if [ "${kind}" == "master" ]; then
    mysql -uroot -p${sqlPwd} -e "CREATE USER 'slave'@'%' IDENTIFIED BY '${sqlPwd}';"
    mysql -uroot -p${sqlPwd} -e "GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'slave'@'%';"
    pos=$(mysql -uroot -p${sqlPwd} -e 'show master status;'| awk '{print $2}' | grep -v 'Position')
  else
    masterSqlPwd=$5
    masterPos=$6
    mysql -uroot -p${sqlPwd} -e "change master to master_host='${mgIP}', master_user='slave', master_password='${masterSqlPwd}', master_port=6033, master_log_file='mysql-bin.000001', master_log_pos=${masterPos}, master_connect_retry=30;"
    mysql -uroot -p${sqlPwd} -e "start slave;"
    sleep 10
    mysql -uroot -p${sqlPwd} -e "show slave status \G;"
  fi
}

init_env "$@"
install_mysql "$@"
echo "MySQL INFO:
User: root
Pass: $sqlPwd
data: /var/lib/mysql
conf: /usr/share/mysql,/etc/my.cnf"
if [ "${kind}" == "master" ]; then
    echo "position: ${pos}"
fi
