#!/bin/bash
#set -x
EDOC2_SERVER="/etc/nginx/conf.d/edoc2_server.conf"
PORT=80
LOCALIP=$(ifconfig eth0 | grep -oP '\d+\..*?(?=\s+n)')
LOCALHASH=$(echo ${LOCALIP} | md5sum | awk '{print $1}')
create_new_container() {
    [[ ! -f 'scale_ip' ]] && touch scale_ip
    DESIRED=$(curl -XGET -H 'Content-Type: application/json' -s --unix-socket /var/run/docker.sock http://${LOCALIP}/services | jq '.[] | .Spec.Name, .Spec.Mode.Replicated.Replicas' | grep -A1 edoc2  | tail -1)
    GLOBALHASH=$(echo $(dig nginx +search +short | /usr/bin/sort | head -n1) | md5sum | awk '{print $1}')
    if [[ $(grep ${IP} scale_ip |tail -n1) != ${IP} ]]; then
        ADD_NUM=$(($DESIRED+1))
        if [[ ${LOCALHASH} == ${GLOBALHASH} ]]; then 
            [[ ${ADD_NUM} -le 10 ]] && docker service scale ${STACKNAMESPACE}_edoc2=${ADD_NUM}
        fi
    fi
    [[ $(grep ${IP} scale_ip) != ${IP} ]] && echo ${IP} >> scale_ip
}
check_tasks(){
    for ((i=1;i<=5;i=i+1)); do
        IPLIST=$(dig edoc2 +short +search | /usr/bin/sort)
        for IP in ${IP_LIST}; do        
        (THREADS_COUNT=$(curl -o /etc/nginx/threadsCount/${IP}_threadsCount.json -s  ${IP}:${PORT}/api/values/1 && jq '.threadsCount' /etc/nginx/threadsCount/${IP}_threadsCount.json)
            if [ $THREADS_COUNT -ge 1500 ];then
                echo -e "$(date '+%Y/%m/%d %H:%M:%S') ${IP}" >> /tmp/bad_ip.log
            fi
        sleep 30) &      
        done
    wait
    done
}

while true; do  
    [[ ! -d '/etc/nginx/threadsCount' ]] && mkdir -p /etc/nginx/threadsCount
    check_tasks
    [[ ! -f '/tmp/bad_ip.log' ]] && touch /tmp/bad_ip.log

    IP_LIST=$(dig edoc2 +short +search | /usr/bin/sort)
    for IP in ${IP_LIST}; do
        if [[ $(cat /tmp/bad_ip.log | grep ${IP} | wc -l) -ge 3 ]]; then
           create_new_container
        fi
    done            

    cat /tmp/bad_ip.log >> /tmp/bad_ip_bak.log

    echo '' > /tmp/bad_ip.log
    echo "--------------------------------------------"
done
