#!/bin/sh

namespaces=100
ksvcs=10

function create_ksvcs {
  for ni in $(seq $namespaces)
  do
    oc new-project foo$ni
    for i in $(seq $ksvcs)
    do
      ksvc_create foo$ni bar$i
    done
  done
}

oc new-project foo || true

function ksvc_create {
	oc create -f - > /dev/null <<EOF
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: $2
  namespace: $1
spec:
  template:
    spec:
      containers:
      - image: gcr.io/knative-samples/helloworld-go
        env:
        - name: TARGET
          value: "Go Sample v1"
EOF
}

function ksvc_delete {
	oc delete -n $1 ksvc $2 > /dev/null
}

function ksvc_wait_for_readiness {
	while oc get ksvc -n $1 $2 -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' | grep -q -v True; do sleep 1; done
}

function ksvcs_wait_for_readiness {
	while [ 0 != $(oc get ksvc --all-namespaces -o custom-columns='READY:.status.conditions[?(@.type=="Ready")].status' --no-headers=true | grep -v True | wc -l) ]; do sleep 1; done
}

function parse_ready_time {
	creation=$(oc get ksvc -n $1 $2 -o jsonpath='{.metadata.creationTimestamp}')
	readiness=$(oc get ksvc -n $1 $2 -o jsonpath='{.status.conditions[?(@.type=="Ready")].lastTransitionTime}')

	revision=$(oc get ksvc -n $1 $2 -o jsonpath='{.status.latestCreatedRevisionName}')
	
	revision_ready=$(oc get revision -n $1 ${revision} -o jsonpath='{.status.conditions[?(@.type=="Ready")].lastTransitionTime}')
	revision_container_healthy=$(oc get revision -n $1 ${revision} -o jsonpath='{.status.conditions[?(@.type=="ContainerHealthy")].lastTransitionTime}')

	creation_unixtime=$(date -d $creation +%s)
	readiness_unixtime=$(date -d $readiness +%s)

	revision_ready_unixtime=$(date -d $revision_ready +%s)
	revision_container_healthy_unixtime=$(date -d $revision_container_healthy +%s)

	echo "revision container healthy in "$((revision_container_healthy_unixtime - creation_unixtime))"s, revision ready in "$((revision_ready_unixtime - creation_unixtime))"s, ksvc ready in "$((readiness_unixtime - creation_unixtime))"s"
}

function check_curl {
        while true
  	do
		url=$(oc get ksvc -n $1 $2 -o jsonpath='{.status.url}')
		echo $url | grep http && break
		sleep 1
	done
  

	while true
	do
		echo "$(date)"
		curl -v $url 2>curl.stderr 1> curl.stdout
		if ! cat curl.stdout | grep -q 'Hello Go Sample v1!'
		then
			cat curl.stderr | grep "^< HTTP"
			if [ $? -eq 1 ]
			then
				cat curl.stderr
			fi
			sleep 1
		else
			break
		fi
	done

	#curl -s $url | grep -q 'Hello Go Sample v1!' || echo "Wrong response from $url"
}

create_ksvcs
ksvcs_wait_for_readiness

