if [ -z "$BASH_VERSION" ]; then exec bash "$0" "$@"; exit; fi

#----------------------------------------------------------------------------------------------------------------
# 변수 선언
echo_line="=========================================================================="
search_tag="spot"
stop_function="spot_stop"
start_function="spot_start"

#----------------------------------------------------------------------------------------------------------------
# aws 인스턴스 조회
_get_aws_status (){
    aws_query="Reservations[].Instances[].[ InstanceId, Tags[?Key=='Name'].Value|[0] ]"
    aws_filter="Name=instance-state-name,Values=running"
    current_ec2_num=`aws ec2 describe-instances --query "${aws_query}" --filter ${aws_filter} --output text | grep ${search_tag} | wc -l`
}

#----------------------------------------------------------------------------------------------------------------
# log 출력
_get_time_log (){
    datetime=`date +'%Y-%m-%d %H:%M:%S'`
    string=$1
    echo "[${datetime}] ${string}"
}

#----------------------------------------------------------------------------------------------------------------
# aws lambda 실행 후 인스턴스 조회하여 성공/실패 여부 체크

_main (){
    lambda_function=$1
    echo ${echo_line}
    if [[ ${lambda_fuction} == *"stop"*  ]]; then
        what_func='stop'
    else
        what_func='start'
    fi

    _get_time_log "[INFO] aws lambda ${lambda_function} start"

    aws lambda invoke --function-name ${lambda_function} --cli-binary-format raw-in-base64-out --payload '{ "key": "value" }' response.json > /tmp/aws_func_result
    #echo "aws lambda invoke --function-name ${lambda_function} --cli-binary-format raw-in-base64-out --payload '{ "key": "value" }' response.json"

    succ_flag=0
    while read line
    do
        if [[ $line == *"200"* ]]; then
          succ_flag=1
          _get_time_log "[INFO] aws lambda ${lambda_function} success!"
          break
        else
          succ_flag=0
        fi
    done < /tmp/aws_func_result

    if [[ ${succ_flag} == 1 ]]; then
        aws lambda invoke --function-name ${lambda_function} out --log-type Tail --query 'LogResult' --output text |  base64 -d > /tmp/aws_func_output
        if [[ ${what_func} == 'stop' ]]; then
            final_ec2_num=0
        else
            final_ec2_num=`grep "Starting" /tmp/aws_func_output | wc -l`
        fi

        num=0
        while true
        do
            _get_aws_status
            num=`echo $(( $num + 1 ))`
            if [[ ${current_ec2_num} == ${final_ec2_num} ]]; then
                _get_time_log "[INFO] aws ${search_tag} instance number: ${final_ec2_num} check success!"
                break
            elif [[ ${num} == 30 ]]; then
                _get_time_log "[Error] time out!"
                break
            else
                _get_time_log "[Retry: ${num}] aws ${search_tag} instance number: ${final_ec2_num} checking..."
            fi
            sleep 5
        done
    else
        echo ${echo_line}
        _get_time_log "[Error] aws lambda ${lambda_function} failed!"
        exit
    fi
    echo ${echo_line}
    #---------------

}
#----------------------------------------------------------------------------------------------------------------
# 실행

_main ${stop_function}

#----------------------------------------------------------------------------------------------------------------
# 임시 파일 삭제

unlink out
unlink response.json
unlink /tmp/aws_func_output
unlink /tmp/aws_func_result
#----------------------------------------------------------------------------------------------------------------
