apiVersion: v1
kind: Pod
metadata:
  name: "{{ include "iceberg-catalog.fullname" . }}-test-bootstrap"
  labels:
    {{- include "iceberg-catalog.labels" . | nindent 4 }}
    component: catalog
  annotations:
    "helm.sh/hook": test
spec:
  serviceAccountName: {{ include "iceberg-catalog.serviceAccountName" . }}
  containers:
    - name: base
      image: debian
      command: ['bash', "-c"]
      args:
        - |
          set -e
          apt-get update -yqq
          apt-get install -yqq curl
          TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
          BOOTSTRAP_URL="http://{{ include "iceberg-catalog.fullname" . }}:8181/management/v1/bootstrap"
          if [ -n "$TOKEN" ]; then
            echo "Found K8s Service Account token"
          else
            echo "No K8s Service Account token found"
          fi
          for i in {1..45}; do
            RESPONSE=$(curl --location "$BOOTSTRAP_URL" \
              --header 'Content-Type: application/json' \
              --header "Authorization: Bearer $TOKEN" \
              --data '{"accept-terms-of-use": true}' \
              --write-out "HTTP_CODE:%{http_code}" --silent --output /dev/null)

            if [[ "$RESPONSE" == *"HTTP_CODE:204"* ]]; then
              echo "Bootstrapping successful"
              exit 0
            else
              echo "Request failed with status code and response: $RESPONSE"
            fi

            sleep 2
          done
          echo "Failed to bootstrap within the given time"
          exit 1
  restartPolicy: Never
