######################################################################
#### function: install rabbitmq_slave
####author:danial_chen
####create date:2019-11-07
####modify date:2019-11-07
######################################################################
#/bin/bash
#useage: sh installmq_slave.sh master_hostname
#eg. sh installmq_slave.sh rabbitmq01

## Useage ##
if [ -z "$1" ]; then
    echo "Useage : sh $0 master_hostname"
	  echo "Default: sh $0 rabbitmq01"
    exit 1
fi

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

# 根据系统来选择使用的版本，麒麟 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 ##
if [ -s /etc/rabbitmq/rabbitmq.conf ]; then
    grep cluster_partition_handling /etc/rabbitmq/rabbitmq.conf >&/dev/null
    if [ $? -eq 0 ];then
        sed -i "/cluster_partition_handling/c cluster_partition_handling = pause_minority" /etc/rabbitmq/rabbitmq.conf
    else
        echo "cluster_partition_handling = pause_minority" >> /etc/rabbitmq/rabbitmq.conf
    fi
else
    echo "cluster_partition_handling = pause_minority" > /etc/rabbitmq/rabbitmq.conf
fi


## Modify config file ## 
#sshpass -p"$password" scp -o "StrictHostKeyChecking no" -r -P"$sshport" "$master_user"@"$master_hostname":/tmp/.erlang.cookie /var/lib/rabbitmq/
#if [ $? -ne 0 ];then
#    exit 2
#fi

# 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

chmod 400 /var/lib/rabbitmq/.erlang.cookie
chown -R rabbitmq:rabbitmq /var/lib/rabbitmq/.erlang.cookie /etc/rabbitmq/rabbitmq.conf

## start rabbitmq service ##
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'

## join cluster ##
rabbitmqctl stop_app
rabbitmqctl join_cluster rabbit@"$master_hostname"
rabbitmqctl start_app

## enable service ##
systemctl daemon-reload
systemctl enable rabbitmq-server
