#!/bin/bash

echo "BEGIN @ $(date +"%T"): Install Cert Manager..."
TLS_SECRET_NAME=$AD_APP_NAME-tls

kubectl create namespace cert-manager

# kubectl apply -f https://raw.githubusercontent.com/jetstack/cert-manager/release-0.11/deploy/manifests/00-crds.yaml --validate=false

helm repo add jetstack https://charts.jetstack.io

helm repo update

# helm install cert-manager --namespace cert-manager --set ingressShim.defaultIssuerName=letsencrypt-prod --set ingressShim.defaultIssuerKind=ClusterIssuer jetstack/cert-manager --version v0.11.0

helm install \
  cert-manager jetstack/cert-manager \
  --namespace cert-manager \
  --set installCRDs=true \
  --set ingressShim.defaultIssuerName=letsencrypt-prod \
  --set ingressShim.defaultIssuerKind=ClusterIssuer

kubectl get pods -n cert-manager

echo "Make sure the cert-manager pods have started BEFORE proceeding."

INPUT_STRING=false
n=50
while [ "$INPUT_STRING" != "true" ]
do
  echo ""
  kubectl get pods -n cert-manager
  if [ "$(kubectl get pods -n cert-manager -o=jsonpath='{.items[0].status.containerStatuses[0].ready}')" == "$(kubectl get pods -n cert-manager -o=jsonpath='{.items[1].status.containerStatuses[0].ready}')" ] && [ "$(kubectl get pods -n cert-manager -o=jsonpath='{.items[2].status.containerStatuses[0].ready}')" == "true" ]; then
    INPUT_STRING=true
  fi
  sleep 5
  if [ "$n" == "0" ]; then
    echo "ERROR. INFINITE LOOP in 5-installCertManager.sh."
    exit 1
  fi
  n=$((n-1))
done

sed "s/{{EMAIL}}/$EMAIL/g" ./TemplateFiles/cluster-issuer-prod.yaml > ./AutoGeneratedFiles/cluster-issuer-prod.yaml

kubectl apply -f ./AutoGeneratedFiles/cluster-issuer-prod.yaml

echo "COMPLETE @ $(date +"%T"): Install Cert Manager"