apiVersion: apps/v1
kind: Deployment
metadata:
  name: dedicated-api-runtime-adapter
spec:
  replicas: 1
  selector:
    matchLabels:
      app: dedicated-api-runtime-adapter
  template:
    metadata:
      labels:
        app: dedicated-api-runtime-adapter
    spec:
      containers:
        - name: adapter
          image: alpine/k8s:1.35.5
          command: [/bin/sh, -ec]
          args:
            - |
              if [ "$CP9_PROVIDER_SOURCE" = Secret ]; then
                kubectl --kubeconfig="$KUBECONFIG" create namespace crossplane-system --dry-run=client -o yaml | kubectl --kubeconfig="$KUBECONFIG" apply -f -
                kubectl --kubeconfig="$KUBECONFIG" create secret generic aws-creds -n crossplane-system --from-file=creds=/var/run/cp9/aws/creds --dry-run=client -o yaml | kubectl --kubeconfig="$KUBECONFIG" apply -f -
              fi
              while true; do
                kubectl --kubeconfig="$KUBECONFIG" get providerconfigs.aws.upbound.io -o json |
                  jq -r --arg source "$CP9_PROVIDER_SOURCE" '.items[] | select(.spec.credentials.source != $source) | .metadata.name' |
                  while read -r name; do
                    if [ "$CP9_PROVIDER_SOURCE" = PodIdentity ]; then
                      patch='{"spec":{"credentials":{"source":"PodIdentity","secretRef":null}}}'
                    else
                      patch='{"spec":{"credentials":{"source":"Secret","secretRef":{"namespace":"crossplane-system","name":"aws-creds","key":"creds"}}}}'
                    fi
                    kubectl --kubeconfig="$KUBECONFIG" patch providerconfigs.aws.upbound.io "$name" --type=merge -p "$patch"
                  done
                sleep 10
              done
          env:
            - name: KUBECONFIG
              value: /var/run/cp9/dedicated-api/classic-provider.kubeconfig
            - name: CP9_PROVIDER_SOURCE
              value: CP9_RUNTIME_PROVIDER_SOURCE
          volumeMounts:
            - name: dedicated-api-kubeconfig
              mountPath: /var/run/cp9/dedicated-api
              readOnly: true
            - name: aws-creds
              mountPath: /var/run/cp9/aws
              readOnly: true
      volumes:
        - name: dedicated-api-kubeconfig
          secret:
            secretName: dedicated-api-kubeconfigs
            items:
              - key: classic-provider.kubeconfig
                path: classic-provider.kubeconfig
        - name: aws-creds
          secret:
            secretName: aws-creds
