set -e
set -o pipefail

usage() {
  echo "Usage: $0 {1|2|3} {1|2|3}"
  echo "First arg is for the apiservice; second is for the vwhc"
  echo "1: kube-root-ca.crt"
  echo "2: openshift-service-ca.crt"
  echo "3: both"
  exit 1
}

[[ $# -eq 2 ]] || usage

# Gather caBundles
kubeca=$(oc get cm kube-root-ca.crt -o jsonpath={.data.ca\\.crt})
svcca=$(oc get cm openshift-service-ca.crt -o jsonpath={.data.service-ca\\.crt})

case $1 in
  1) svcbundle="$kubeca";;
  2) svcbundle="$svcca";;
  3) svcbundle="$kubeca
$svcca";;
  *) usage;;
esac

case $2 in
  1) vwhcbundle="$kubeca";;
  2) vwhcbundle="$svcca";;
  3) vwhcbundle="$kubeca
$svcca";;
  *) usage;;
esac

# Replace caBundles
oc patch apiservice v1.admission.hive.openshift.io \
    -p '{"spec": {"caBundle": "'$(base64 -w 0 <<< "$svcbundle")'"}}'
oc patch validatingwebhookconfigurations.admissionregistration.k8s.io dnszonevalidators.admission.hive.openshift.io \
    -p '{"webhooks": [{"name": "dnszonevalidators.admission.hive.openshift.io", "clientConfig": {"caBundle": "'$(base64 -w 0 <<< "$vwhcbundle")'"}}]}'

# Bounce kaso
oc delete -n openshift-kube-apiserver-operator po -l app=kube-apiserver-operator
oc wait   -n openshift-kube-apiserver-operator rs -l app=kube-apiserver-operator --for=jsonpath={.status.readyReplicas}=1 
oc wait   -n openshift-kube-apiserver-operator po -l app=kube-apiserver-operator --for=condition=Ready

sleep 5

# Test the webhook.
# GOOD: Error from server (BadRequest): error when creating "STDIN": admission webhook "dnszonevalidators.admission.hive.openshift.io" denied the request: Failed validation: a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')
# BAD:  Error from server (InternalError): error when creating "STDIN": Internal error occurred: failed calling webhook "dnszonevalidators.admission.hive.openshift.io": failed to call webhook: the server is currently unable to handle the request
echo; echo
echo '{"apiVersion": "hive.openshift.io/v1", "kind": "DNSZone", "metadata": {"name": "badzone"}, "spec": {"zone": "invalid_dns"}}' | oc create -f - || true

# Look for our error.
# GOOD: <No output>
# BAD:  W0619 20:40:30.754463       1 degraded_webhook.go:147] failed to connect to webhook "dnszonevalidators.admission.hive.openshift.io" via service "kubernetes.default.svc:443": tls: failed to verify certificate: x509: certificate signed by unknown authority
echo; echo
oc logs -n openshift-kube-apiserver-operator deploy/kube-apiserver-operator -f | grep dnszone

