#!/bin/bash
# Author:  EinicYeo <einicyeo AT gmail.com>
# BLOG:  https://www.infvie.com
#
# Notes: EnvoyinStack for CentOS/RedHat 6+

Install_rabbitmq_server() {
  pushd ${envoyinstack_dir}/src > /dev/null
  erl=`rpm -qa|grep erlang`
  if [ -z $erl ];then
      yum -y install erlang 
  fi
  if [ -n $erl ];then
     echo "${CSUCCESS}Erlang installed successfully! ${CEND}"
  else
     echo "${CFAILURE}Erlang installed failed! ${CEND}"
     exit
  fi
  socat=`rpm -qa|grep socat`
  if [ -z $socat ];then
       yum -y install socat
  fi
  
  if [ -n $socat ];then
     echo "${CSUCCESS}Socat installed successfully! ${CEND}"
  else
     echo "${CFAILURE}Socat installed failed! ${CEND}"
     exit
  fi
  tar xf rabbitmq-server-generic-unix-${rabbitmq_ver}.tar && mv rabbitmq_server-${rabbitmq_ver} ${rabbitmq_install_dir}
  ln -s ${rabbitmq_install_dir}/sbin/* /usr/sbin/
  
  id -u rabbitmq >/dev/null 2>&1
  [ $? -ne 0 ] && useradd -M -s /sbin/nologin rabbitmq
  /bin/cp -rf ../config/rabbitmq-defaults ${rabbitmq_install_dir}/sbin/
  mkdir -p /var/lib/rabbitmq && mkdir -p /data/rabbitmq/etc && mkdir -p /home/rabbitmq
  /bin/cp ../config/rabbitmq.conf /data/rabbitmq/etc/
  chown -R rabbitmq:rabbitmq ${rabbitmq_install_dir} /var/lib/rabbitmq /home/rabbitmq /data/rabbitmq
  
  if [ -e /bin/systemctl ]; then
    /bin/cp ../init.d/rabbitmq-server.service /usr/lib/systemd/system/
    sed -i "s@/usr/local/rabbitmq@${rabbitmq_install_dir}@g" /usr/lib/systemd/system/rabbitmq-server.service
    systemctl enable rabbitmq-server && systemctl start rabbitmq-server
    cp -rf /home/rabbitmq/.erlang.cookie /root/.erlang.cookie
    if [ -e /usr/lib/systemd/system/rabbitmq-server.service ];then
      echo "${CSUCCESS}Rabbitmq-server installed successfully! ${CEND}"
      for plugins in ${rabbitmq_modules_options[@]}
      do
         ${rabbitmq_install_dir}/sbin/rabbitmq-plugins enable $plugins
         echo "${CSUCCESS}Rabbitmq-server $plugins installed successfully! ${CEND}"
     done
      sed -i "s+^rabbitmqpwd.*+rabbitmqpwd='${rabbitmqpwd}'+" ../config/options.conf
      ${rabbitmq_install_dir}/sbin/rabbitmqctl add_user root ${rabbitmqpwd}
      ${rabbitmq_install_dir}/sbin/rabbitmqctl set_permissions -p "/" root ".*" ".*" ".*"
      ${rabbitmq_install_dir}/sbin/rabbitmqctl set_user_tags root administrator
      ${rabbitmq_install_dir}/sbin/rabbitmqctl delete_user guest
    fi
   echo "" && systemctl restart rabbitmq-server.service && pid=`ps aux|grep rabbitmq-server|grep grep -v`
   if [ -z $pid ];then
      echo "${CSUCCESS}Rabbitmq-server restart successfully! ${CEND}"
   else
      echo "${CFAILURE}Rabbitmq-server start failed, Please contact the author! ${CEND}"
   fi
  else
    rm -rf ${rabbitmq_install_dir}
    echo "${CFAILURE}Rabbitmq-server install failed, Please contact the author! ${CEND}" && lsb_release -a
    kill -9 $$
  fi
  popd > /dev/null
}
