#!/bin/bash
#set -x
while true
do

    EDOC2_SERVER='/etc/nginx/conf.d/edoc2_server.conf' 

    echo "upstream edoc2_ip {" > ${EDOC2_SERVER}
    if [ "${IP_HASH}" != "false" ];then
         echo 'hash $clientRealIp consistent;' >> ${EDOC2_SERVER}
    fi
    IP_LIST=$(dig edoc2 +search +short | /usr/bin/sort)
    if [ -n "${IP_LIST}" ];then
    	for IP in ${IP_LIST}
    	do 
       	    echo "server ${IP} max_fails=100 fail_timeout=10s;" >> ${EDOC2_SERVER}
    	done
    else
        echo "server edoc2 max_fails=100 fail_timeout=10s;" >> ${EDOC2_SERVER} 
    fi
    echo "keepalive 256;" >> ${EDOC2_SERVER}
    echo "}" >> ${EDOC2_SERVER}

    # del bad_ip
    if [ "$EDOC2_SCALE" == "true" ]; then
      for IP in ${IP_LIST}; do
  	  [[ ! -f '/tmp/bad_ip_bak.log' ]] && touch /tmp/bad_ip_bak.log
    	  if [[ $(cat /tmp/bad_ip_bak.log | grep ${IP} | wc -l) -ge 3 ]]; then
    		sed -i "/$IP/d" ${EDOC2_SERVER}
	  fi
      done
    fi    

    if [ ! -f '/etc/nginx/edoc2_server.md5' ];then
        /usr/bin/md5sum ${EDOC2_SERVER}|cut -f1 -d ' ' > /etc/nginx/edoc2_server.md5
    else
        if [ "$(/usr/bin/md5sum ${EDOC2_SERVER}|cut -f1 -d ' ')" != "$(cat /etc/nginx/edoc2_server.md5)" ];then   
             /usr/bin/md5sum ${EDOC2_SERVER}|cut -f1 -d ' ' > /etc/nginx/edoc2_server.md5
             /usr/sbin/nginx -t 
             if [ $? = 0 ];then
	     	/usr/sbin/nginx -s reload 
		echo "$(date '+%Y/%m/%d %H:%M:%S') edoc2 config change,reload nginx" >> /tmp/nginx_reload.log 
	     else
             	echo "$(date '+%Y/%m/%d %H:%M:%S') change md5 reload nginx." > /etc/nginx/edoc2_server.md5			
	     fi
        fi
    fi
    sleep 5
done
