apiVersion: v1
kind: ConfigMap
metadata:
  name: ingress-scripts
  annotations:
    "helm.sh/hook": "post-install,post-upgrade"
    "helm.sh/hook-weight": "10"
data:
  update-ingress-host.sh: |
    #!/bin/sh
    host=${HOST:-airy.core}
    for ingress in $(kubectl get ingress -l core.airy.co/managed=true -o jsonpath='{.items[*].metadata.name}'); do
      kubectl get ingress ${ingress} -o json | jq "(.spec.rules[0].host=\"${host}\")" | kubectl apply -f -
    done
  update-ingress-tls.sh: |
    #!/bin/sh
    host=${HOST:-airy.core}
    for ingress in $(kubectl get ingress -l core.airy.co/managed=true -o jsonpath='{.items[*].metadata.name}'); do
      kubectl get ingress ${ingress} -o json | jq "(.spec.tls[0].hosts[0]=\"${host}\" | .spec.tls[0].secretName=\"${ingress}\")" | kubectl apply -f -
    done
  update-ingress-annotation.sh: |
    #!/bin/sh
    issuer=${ISSUER}
    for ingress in $(kubectl get ingress -l core.airy.co/managed=true -o jsonpath='{.items[*].metadata.name}'); do
      kubectl annotate ingress ${ingress} cert-manager.io/cluster-issuer=${issuer} --overwrite
    done
  update-configmap-host.sh: |
    #!/bin/sh
    host=${HOST:-airy.core}
    protocol=${PROTOCOL:-http}
    kubectl patch configmap core-config -p "{\"data\":{\"API_HOST\":\"${protocol}://${host}\"}}" --type merge
  wait-for-loadbalancer.sh: |
    #!/bin/sh
    delay=${DELAY:-10}
    host=$(kubectl -n kube-system get service  ingress-nginx-controller -o jsonpath='{.status.loadBalancer.ingress[0].*}')
    while test -z "${host}"; do
      echo "Waiting for loadbalancer to be created..."
      sleep ${delay}
      host=$(kubectl -n kube-system get service  ingress-nginx-controller -o jsonpath='{.status.loadBalancer.ingress[0].*}')
    done
  update-ingress-lb.sh: |
    #!/bin/sh
    host=$(kubectl -n kube-system get service  ingress-nginx-controller -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
    if test "${host}"; then
      for ingress in $(kubectl get ingress -l core.airy.co/managed=true -o jsonpath='{.items[*].metadata.name}'); do
        kubectl get ingress ${ingress} -o json | jq "(.spec.rules[0].host=\"${host}\")" | kubectl apply -f -
      done
    fi
  update-configmap-lb.sh: |
    #!/bin/sh
    protocol=${PROTOCOL:-http}
    host=$(kubectl -n kube-system get service  ingress-nginx-controller -o jsonpath='{.status.loadBalancer.ingress[0].*}')
    kubectl patch configmap core-config -p "{\"data\":{\"API_HOST\":\"${protocol}://${host}\"}}" --type merge
