######################################################################
#### 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 master_user password
#eg. sh installmq_slave.sh rabbitmq01 ksuser Kingdee@2019

## Useage ##
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ];then
    echo "Useage : sh $0 master_hostname masret_user password sshport"
	echo "Default: sh $0 rabbitmq01 kduser Kingdee@2019 22"
    exit 1
fi

## ENV ##
source /etc/profile
pd=$PWD
master_hostname=$1
master_user=$2
password=$3
sshport=$4
rabbitmq_version="rabbitmq-3.8.18"

## install rabbitmq ##
tar -zxf $pd/$rabbitmq_version.tar.gz
chmod -R 755 $pd/$rabbitmq_version
cd $pd/$rabbitmq_version
yum localinstall sshpass-1.06-2.el7.x86_64.rpm  erlang-23.3.1-1.el7.x86_64.rpm  rabbitmq-server-3.8.18-1.el7.noarch.rpm  tcp_wrappers-7.6-77.el7.x86_64.rpm  socat-1.7.3.2-1.1.el7.x86_64.rpm -y

## 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
chmod 400 /var/lib/rabbitmq/.erlang.cookie
chown -R rabbitmq:rabbitmq /var/lib/rabbitmq/.erlang.cookie /etc/rabbitmq/rabbitmq.conf

## start rabbitmq service ##
systemctl restart rabbitmq-server
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
