#!/bin/bash
while true
do

    TRANSPORT_SERVER='/etc/nginx/conf.d/transport_server.conf'

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

    if [ ! -f '/etc/nginx/transport_server.md5' ];then
        /usr/bin/md5sum ${TRANSPORT_SERVER}|cut -f1 -d ' ' > /etc/nginx/transport_server.md5
    else
        if [ "$(/usr/bin/md5sum ${TRANSPORT_SERVER}|cut -f1 -d ' ')" != "$(cat /etc/nginx/transport_server.md5)" ];then   
             /usr/bin/md5sum ${TRANSPORT_SERVER}|cut -f1 -d ' ' > /etc/nginx/transport_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 10
done





