#!/bin/bash

if [ $# -ne 2 ]; then
  # Print usage
  echo 'Error! wrong number of arguments'
  echo 'usage:'
  echo 'w8/ready.w8 what-to-wait-for in-what-namespace'
  exit 1
fi

qrunning () {
  countone=1
  #timeout for 15 minutes"
  while [ $countone -lt 151 ]
  do
    printf '.'
    RESULT=$(kubectl get --namespace=$2 -o template pod --template={{.status.phase}} $1 2>/dev/null | grep Running)
    if [ "$RESULT" ]; then
        echo '.'
        break
    fi
    countone=`expr $countone + 1`
    sleep 3
  done
}

qready () {
  countone=1
  # timeout for 15 minutes
  while [ $countone -lt 151 ]
  do
    printf '.'
    RESULT=$(kubectl get --namespace=$2 pods/$1 -o json 2>/dev/null | jq -r \
     '. | select(.status.phase = ([ .status.conditions[] | select(.type == "Ready" and .state == true) ] | length ) == 1 ) | .metadata.namespace + "/" + .metadata.name' )
    if [ "$RESULT" ]; then
      if [[ $USE_STRICT_W8 == 'true' ]]; then
        # Ready column can look like '0/1' or '1/3', this hacky bash checks if the fraction = 1
        NOT_READY_PODS=$(kubectl get pods -n $2 | grep $1| awk '{print $2}'| sed 's,/, ,g' | awk '{print $2 " - " $1}'| bc)
        if [[ $NOT_READY_PODS -eq 0 ]]; then
          echo '.'
          break
        fi
      else
        READY_PODS=$(kubectl get pods -n $2 | grep $1 | awk '{print $2}' | sed 's,/, ,g' | awk '{print $1}')
        if [[ $READY_PODS -gt 0 ]]; then
          echo '.'
          break
        fi
      fi
    fi
    countone=`expr $countone + 1`
    sleep 3
  done
}

main () {
  echo 'Ready.w8'
  if [[ $EXCLUDE_POD ]]; then
    KUBE_SELECTED_PODS=$(kubectl get pods --namespace=$2 2>/dev/null |awk '{print $1}'|grep $1 |grep -v $EXCLUDE_POD  |tr '\n' ' ')
  else
    KUBE_SELECTED_PODS=$(kubectl get pods --namespace=$2 2>/dev/null |awk '{print $1}'|grep $1 |tr '\n' ' ')
  fi
  for this_pod in $KUBE_SELECTED_PODS; do
    echo "testing $this_pod  in the namespace $2 for running and readiness"
    qrunning $this_pod $2
    qready $this_pod $2
  done
}

time main $@
