{{- $enabled := eq (include "osdu-developer-init.isEnabled" .) "1" -}}
{{- $namespace := .Release.Namespace -}}
{{- if and $enabled .Values.jobs.entitlementInit }}
---
apiVersion: batch/v1
kind: Job
metadata:
  name: entitlement-init
  namespace: {{ $namespace }}
spec:
  ttlSecondsAfterFinished: 120
  template:
    metadata:
      labels:
        azure.workload.identity/use: "true"
    spec:
      serviceAccountName: workload-identity-sa
      volumes:
      - name: script
        configMap:
          name: entitlement-init-script
          defaultMode: 0500
      initContainers:
      - name: data-seed
        image: mcr.microsoft.com/azure-cli:cbl-mariner2.0
        command:
        - script/init.sh
        volumeMounts:
          - name: script
            mountPath: "/script"
        env:
          - name: NAMESPACE
            value: {{ $namespace }}
          - name: AZURE_TENANT_ID
            value: {{ .Values.tenantId | quote }}
          - name: AZURE_AD_APPLICATION_ID
            value: {{ .Values.clientId | quote }}
          - name: PARTITION
            value: {{ .Values.partition | quote }}
      containers:
      - name: sleep
        image: istio/base
        command: ["/bin/sleep", "30"]
        volumeMounts:  # Ensure this container also mounts the volume if needed
          - name: script
            mountPath: "/script"
      restartPolicy: Never
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: entitlement-init-script
  namespace: {{ $namespace }}
data:
  init.sh: |
    #!/usr/bin/env sh
    set -euo pipefail
    set -o nounset

    tdnf install -y curl jq

    echo "=================================================================="
    echo "  Logging in using Workload Identity"
    echo "=================================================================="

    # Login using the federated token from the environment variable
    az login --federated-token "$(cat ${AZURE_FEDERATED_TOKEN_FILE})" \
        --service-principal \
        -u ${AZURE_CLIENT_ID} \
        -t ${AZURE_TENANT_ID}

    # Get token (no resource needed)
    TOKEN=$(az account get-access-token --resource "https://management.azure.com/" --query accessToken -o tsv)

    OUTPUT=$(curl -s -w "%{http_code}" --request POST \
      --url http://entitlements.{{ $namespace }}/api/entitlements/v2/tenant-provisioning \
      --header "Host: entitlements.{{ $namespace }}" \
      --header "accept: application/json" \
      --header "content-type: application/json" \
      --header "authorization: Bearer $TOKEN" \
      --header "data-partition-id: ${PARTITION}")

    HTTP_STATUS_CODE=$(echo $OUTPUT | grep -oE '[0-9]{3}$')
    BODY=${OUTPUT%???}

    if [ "$HTTP_STATUS_CODE" == "200" ]; then
      echo "Success: $(echo "$BODY" | jq .)"
    else
      echo "Error: Unexpected HTTP status code $HTTP_STATUS_CODE"
      echo "Response body: $BODY"
      exit 1
    fi

    exit 0
{{- end }}