######################################################################
#### function: install rabbitmq_master
####author:danial_chen
####create date:2019-11-07
####modify date:2019-11-07
######################################################################
#/bin/bash
#useage: sh installmq_master.sh

set +e
## ENV ##
source /etc/profile
set -e
pd=$PWD

# 根据系统来选择使用的版本，麒麟 3.7.23，centos 3.8.18，默认3.8.18
rabbitmq_version="rabbitmq-3.8.18"
if [ -f /etc/os-release ]; then
  id=$(cat /etc/os-release | grep -e "^ID=" | awk -F '=' '{print $2}')
  if [[ $id == "\"kylin\"" ]]; then
    rabbitmq_version="rabbitmq-3.7.23"
  elif [[ $id == "\"rhel\"" ]]; then
    mkdir -p /var/lib/rabbitmq
    chown -R rabbitmq:rabbitmq /var/lib/rabbitmq
  fi
fi

echo "install rabbitmq version is $rabbitmq_version"
## install rabbitmq ##
tar -zxf $pd/$rabbitmq_version.tar.gz
chmod -R 755 $pd/$rabbitmq_version
cd $pd/$rabbitmq_version
rpm -ivh --nosignature --force --nodeps *.rpm
if [ ! -d /etc/rabbitmq ]; then mkdir /etc/rabbitmq; fi
## parameter of Prevent fissure ##
rm -rf /etc/rabbitmq/rabbitmq.conf
cat > /etc/rabbitmq/rabbitmq.conf << EOF
cluster_partition_handling = pause_minority
net_ticktime = 120
EOF

# add group and user if not exist
groupadd -f rabbitmq
exist=$(grep "^rabbitmq:" /etc/passwd | wc -l)
if [[ ${exist} -eq 0 ]]; then
  useradd -g rabbitmq -d /var/lib/rabbitmq -s /sbin/nologin rabbitmq
fi

# start rabbitmq ##
chown -R rabbitmq:rabbitmq /etc/rabbitmq
systemctl restart rabbitmq-server
su -s /bin/bash rabbitmq -c '/usr/lib/rabbitmq/bin/rabbitmq-plugins enable rabbitmq_management'

#copy .erlang.cookie to /tmp/
cp -rp /var/lib/rabbitmq/.erlang.cookie /tmp/
chmod -R 755 /tmp/.erlang.cookie
chown rabbitmq. /etc/rabbitmq/rabbitmq.conf

## register systemd ##
systemctl daemon-reload
systemctl enable rabbitmq-server
