{{- if and (hasKey .Values "tls") (hasKey .Values.tls "enabled") .Values.tls.enabled (hasKey .Values.tls "secretName") }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ template "landing.name" . }}-tls-sync
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ template "landing.name" . }}
  annotations:
    # This annotation is used to automatically trigger the job when the certificate is updated
    cert-manager.io/certificate-name: {{ .Values.tls.secretName }}
    # Add a unique identifier so each deployment creates a new job
    "helm.sh/hook": post-install,post-upgrade
    "helm.sh/hook-weight": "0"
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  ttlSecondsAfterFinished: 3600
  template:
    metadata:
      labels:
        app: {{ template "landing.name" . }}
    spec:
      serviceAccountName: {{ .Values.serviceAccount.name }}
      restartPolicy: OnFailure
      containers:
      - name: sync-tls-cert
        image: registry.redhat.io/openshift4/ose-cli:latest
        command:
        - /bin/bash
        - -c
        - |
          set -e
          echo "Waiting for certificate to be ready..."
          while ! oc get secret {{ .Values.tls.secretName }} -n {{ .Release.Namespace }} &>/dev/null; do
            echo "Certificate secret not found yet, waiting..."
            sleep 5
          done
          
          echo "Certificate found, syncing to router namespace..."
          # Get the original certificate
          oc get secret {{ .Values.tls.secretName }} -n {{ .Release.Namespace }} -o yaml > /tmp/cert.yaml
          
          # Modify the YAML for the new namespace
          sed -i "s/namespace: {{ .Release.Namespace }}/namespace: openshift-ingress/" /tmp/cert.yaml
          # Remove resource version and other metadata that would prevent creation
          sed -i '/resourceVersion:/d' /tmp/cert.yaml
          sed -i '/uid:/d' /tmp/cert.yaml
          sed -i '/creationTimestamp:/d' /tmp/cert.yaml
          sed -i '/selfLink:/d' /tmp/cert.yaml
          sed -i '/managedFields:/,/manager:/d' /tmp/cert.yaml
          sed -i '/ownerReferences:/,/kind:/d' /tmp/cert.yaml
          
          # Create or update the secret in the router namespace
          echo "Applying TLS secret to openshift-ingress namespace..."
          oc apply -f /tmp/cert.yaml
          
          echo "TLS certificate synced successfully!"
{{- end }} 