######################################################################
#### function: init rabbitmq
####author:danial_chen
####create date:2019-11-07
####modify date:2019-11-07
######################################################################
#/bin/bash
#useage: sh initmq.sh mq_user mq_password ierp_vhost mc_vhost
#eg. sh initmq.sh admin ***** next mc

set -e
## ENV ##
mq_user=$1
mq_password=$2
if [ -z "$mq_password" ];then
  echo "mq_password is empty"
  exit 10
fi
ierp_vhost=$3
mc_vhost=$4
export mq_user=${mq_user:-admin}
export mq_password=${mq_password}
export ierp_vhost=${ierp_vhost:-ierp}
export mc_vhost=${mc_vhost:-mc}

## add rabbitmq_user ##
exists=`rabbitmqctl list_users|grep ^$mq_user|wc -l`
if [[ $exists -gt 0 ]];then
  echo "user $mq_user exist, delete first"
  rabbitmqctl delete_user $mq_user
fi
rabbitmqctl add_user $mq_user $mq_password
rabbitmqctl set_user_tags $mq_user administrator

## add rabbitmq_vhost ##
rabbitmqctl add_vhost $ierp_vhost
rabbitmqctl  set_permissions -p $ierp_vhost $mq_user '.*'  '.*'  '.*'
rabbitmqctl set_policy -p  $ierp_vhost  ha-allqueue "^"  '{"ha-mode":"all"}'
rabbitmqctl add_vhost $mc_vhost
rabbitmqctl  set_permissions -p $mc_vhost $mq_user '.*'  '.*'  '.*'
rabbitmqctl set_policy -p  $mc_vhost  ha-allqueue "^"  '{"ha-mode":"all"}'
