#!/bin/sh

namespaces=20
ksvcs=5

function ksvc {
	cat <<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 create {
	oc create -f -
}

function delete {
 	oc delete -f -
}

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 ksvcs_ns_wait_for_readiness {
	while [ 0 != $(oc get ksvc -n $1 -o custom-columns='READY:.status.conditions[?(@.type=="Ready")].status' --no-headers=true | grep -v True | wc -l) ]; do sleep 1; done
}


function create_wait_delete_repeat {
  j=0
  while true
  do
    tmp=$(mktemp)

    for i in $(seq $ksvcs)
    do
      j=$((j+1))
      ksvc foo$ni bar$j >> $tmp
    done

    create < $tmp
    ksvcs_ns_wait_for_readiness $1
    delete < $tmp

    rm $tmp
  done
}

function create_wait_and_delete_ksvcs_in_repeat {
  for ni in $(seq $namespaces)
  do
    oc new-project foo$ni
    create_wait_delete_repeat foo$ni & 
  done

  wait
}


create_wait_and_delete_ksvcs_in_repeat

