HAPROXY_CONFIG='./haproxy.cfg'
MYSQL_SERVER=./opt/mysql_server
mysql0="192.168.251.176:33361"
mysql1="192.168.251.154:33362"
mysql2="192.168.251.152:33363"
MYSQL_MEM=($mysql0 $mysql1 $mysql2)
MD5_FILE=./opt/haproxy_config.md5
PID_FILE=/run/haproxy.pid


mysqla=mysql-mgra-0.mysql-mgra.edoc2.svc.cluster.local
mysqlb=mysql-mgrb-0.mysql-mgrb.edoc2.svc.cluster.local
mysqlb=mysql-mgrc-0.mysql-mgrc.edoc2.svc.cluster.local

for 
mysql_status1=`mysql -urepl -pXjb0^DDy -h -P33361 -e "select * from performance_schema.replication_group_members;" | grep mysql-mgra-0.mysql-mgra.edoc2.svc.cluster.local | awk -F " " '{print $5}'`
mysql_status2=`mysql -urepl -pXjb0^DDy -h192.168.251.176 -P33361 -e "select * from performance_schema.replication_group_members;" | grep mysql-mgra-0.mysql-mgra.edoc2.svc.cluster.local | awk -F " " '{print $5}'`


if [ ! -f ${MYSQL_SERVER} ];then
    touch ${MYSQL_SERVER}
fi
while true
do
    for HOSTNAME in ${MYSQL_MEM[@]}
    do
      echo $HOSTNAME
      HOST_IP=$(/usr/bin/dig ${HOSTNAME} +short +search)
      echo "${HOST_IP}"
        if [ -n "${HOST_IP}" ] && ! echo "${HOST_IP}"|grep 'timed out';then
            sed -i /${HOSTNAME}/d ${MYSQL_SERVER}
            echo "11111111111111111111111111111 ${HOSTNAME} ${HOST_IP}"
            echo "${HOSTNAME} ${HOST_IP}" >> ${MYSQL_SERVER} 
        fi
    done
    if [ $(wc -l ${MYSQL_SERVER}|awk '{print $1}') -ge 2 ];then
        
        for SEDNAME in ${MYSQL_MEM[@]}
        do
           if grep ${SEDNAME} ${MYSQL_SERVER} &>/dev/null;then
               echo "2222222222222222222222222222222222222222222222222"
               echo "${SEDNAME}"
               sed -i "/${SEDNAME}/ s/#//g" ${HAPROXY_CONFIG}
           else
               egrep "^#.*${SEDNAME}" ${HAPROXY_CONFIG} &> /dev/null
               echo "3333333333333333333333333333333333333333333333333"
               if [ $? -ne 0 ];then
                   sed -i "/${SEDNAME}/ s/^/#/g" ${HAPROXY_CONFIG}
               fi
           fi
        done
    fi
    if [ ! -f ${PID_FILE} ];then
       /usr/bin/md5sum ${HAPROXY_CONFIG}|cut -f1 -d ' ' > ${MD5_FILE}
       echo "start haproxy"
       #haproxy -W -db -f ${HAPROXY_CONFIG} -p ${PID_FILE} &
    else
        if [ "$(/usr/bin/md5sum ${HAPROXY_CONFIG}|cut -f1 -d ' ')" != "$(cat ${MD5_FILE})" ];then   
            /usr/bin/md5sum ${HAPROXY_CONFIG}|cut -f1 -d ' ' > ${MD5_FILE}
           echo "reload haproxy"
           #haproxy -W -db -f ${HAPROXY_CONFIG} -st $(cat ${PID_FILE}) -p ${PID_FILE} &
        fi
    fi
    sleep 5
done
