#!/usr/bin/env bash

function ack()
{
    ack_phrase="$1"
    log_path="$2"
    max_wait_log_generate_time="$3"
    max_wait_ack_time="$4"
    wait_log_generate_time=0
    wait_ack_time=0
    echo "begin acknowledge whether the deploy start OK, ACK_PHRASE=${ack_phrase}, log_path=${log_path}"
    while [ ! -f ${log_path} ]
    do
        echo "wait_log_generate_time is ${wait_log_generate_time}, max_wait_log_generate_time is ${max_wait_log_generate_time} "
        if ((${wait_log_generate_time}>${max_wait_log_generate_time}))
        then
            echo "the log generated time exceed the limit"
            exit -1
        fi
        echo 'the log does not exist, wait for 5 seconds'
        sleep 5
        let "wait_log_generate_time+=5"
    done
    echo "listen for the log ack..."
    for ((i=0;;))
    do
        bootstrap_flag=`cat ${log_path} |grep "${ack_phrase}"| wc -l`
        if [ "${bootstrap_flag}" = 0 ] && [ "${max_wait_ack_time}" -gt "${wait_ack_time}" ]
        then
            sleep 5
            let "wait_ack_time+=5"
            echo "waiting for bootstrap flag for ${wait_ack_time}"
        elif [ "${bootstrap_flag}" = 1 ]
        then
            echo "server is start~"
            exit 0
        else
            echo "server not startup in ${max_wait_ack_time} seconds..."
            exit -1
        fi
    done
}

ack "$1" $2 $3 $4