#!/bin/bash

# Copyright 2017 The Openstack-Helm Authors.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
set -e

# Default wait timeout is 180 seconds
: ${KUBECONFIG:="/etc/kubernetes/admin.conf"}
export KUBECONFIG=${KUBECONFIG}

end=$(date +%s)
if ! [ -z $2 ]; then
 end=$((end + $2))
else
 end=$((end + 180))
fi
while true; do
    NUMBER_OF_NODES=$(kubectl get nodes --no-headers -o name | wc -l)
    NUMBER_OF_NODES_EXPECTED=$(($(cat /etc/nodepool/sub_nodes_private | wc -l) + 1))
    [ $NUMBER_OF_NODES -eq $NUMBER_OF_NODES_EXPECTED ] && \
        NODES_ONLINE="True" || NODES_ONLINE="False"
    while read SUB_NODE; do
      echo $SUB_NODE | grep -q ^Ready && NODES_READY="True" || NODES_READY="False"
    done < <(kubectl get nodes --no-headers | awk '{ print $2 }')
    [ $NODES_ONLINE == "True" -a $NODES_READY == "True"  ] && \
        break || true
    sleep 5
    now=$(date +%s)
    [ $now -gt $end ] && echo "Nodes Failed to be ready in time." && \
        kubectl get nodes -o wide && exit -1
done
