#!/bin/sh

export namespace=${1:-foobar}

oc new-project $namespace || true

function ksvc_create {
	oc create -f - > /dev/null <<EOF
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: $1
  namespace: $namespace
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 $namespace ksvc $1 > /dev/null
}

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

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

	revision=$(oc get ksvc -n $namespace $1 -o jsonpath='{.status.latestCreatedRevisionName}')
	
	revision_ready=$(oc get revision -n $namespace ${revision} -o jsonpath='{.status.conditions[?(@.type=="Ready")].lastTransitionTime}')
	revision_container_healthy=$(oc get revision -n $namespace ${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 {
	url=$(oc get ksvc -n $namespace $1 -o jsonpath='{.status.url}')

	while true
	do
		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"
}

i=0
while true
do
	i=$(($i + 1))
	name=testfoo$i
	ksvc_create $name
	ksvc_wait_for_readiness $name
	check_curl $name
	parse_ready_time $name
	ksvc_delete $name
done

