apiVersion: batch/v1
kind: Job
metadata:
  annotations:
    argocd.argoproj.io/sync-wave: "260"
  name: updated-image-integration-creds
spec:
  template:
    spec:
      containers:
        - image: image-registry.openshift-image-registry.svc:5000/openshift/cli:latest
          env:
            - name: PASSWORD
              valueFrom:
                secretKeyRef:
                  name: central-htpasswd
                  key: password
          command:
            - /bin/bash
            - -c
            - |
              #!/usr/bin/env bash
              # Create a temporary python script to handle the JSON transformations.
              cat << EOF > /tmp/jsontransform.py
              import sys,json;
              # Read temporary integrations list.
              intfile = open("/tmp/imageintegrations.json",'r')
              jsonobj = json.loads(intfile.read())
              intfile.close()
              # Print list for debug purposes
              print(json.dumps(jsonobj, indent=2))
              print(sys.argv[1]) # Service Account name.
              print(sys.argv[2]) # Service Account Token.
              for integration in jsonobj["integrations"]:
                  if "openshift-image-registry" in integration["name"]:
                      integrationId = integration["id"];
                      integration.pop("id", None)
                      integration["name"] = integration["name"].replace("Autogenerated", "GitOps Job generated")
                      integration["autogenerated"] = False
                      integration["skipTestIntegration"] = False
                      integration["docker"]["username"] = sys.argv[1]
                      integration["docker"]["password"] = sys.argv[2]
                      with open("/tmp/integration_" + integrationId + "_data.json", 'w') as patchfile:
                          json.dump(integration, patchfile, indent=2)
              EOF
              # Wait for central to be ready
              attempt_counter=0
              max_attempts=20
              echo "Waiting for central to be available..."
              until $(curl -k --output /dev/null --silent --head --fail https://central); do
                  if [ ${attempt_counter} -eq ${max_attempts} ];then
                    echo "Max attempts reached"
                    exit 1
                  fi
                  printf '.'
                  attempt_counter=$(($attempt_counter+1))
                  echo "Made attempt $attempt_counter, waiting..."
                  sleep 10
              done
              # It takes some time for default integrations to be created, so sleep for 3min.
              sleep 180
              echo "Getting stackrox-image-puller service account token and Central URL."
              SATOKEN=`oc sa get-token stackrox-image-puller -n stackrox`
              CENTRAL_URL="https://`oc -n stackrox get route central -o go-template='{{.spec.host}}'`"
              API="/v1/imageintegrations"
              echo "Central API endpoint for image integrations: $CENTRAL_URL$API"
              echo "Getting default image integrations list."
              curl -k -o \
                  /tmp/imageintegrations.json \
                  -X GET -u "admin:$PASSWORD" \
                  -H "Content-Type: application/json" \
                  $CENTRAL_URL$API
              echo "Parsing and updating internal registry integrations."
              python3 /tmp/jsontransform.py stackrox-image-puller $SATOKEN
              # Execute PUT commands to update ocp internal registry integrations.
              for file in `ls /tmp | grep "integration_"`
              do
                  INTID=${file#*_}
                  INTID=${INTID%_*}
                  # Old URL if using PUT
                  # echo "URL: $CENTRAL_URL$API/$INTID"
                  echo "URL: $CENTRAL_URL$API"
                  echo "File ID: $INTID"
                  curl -k \
                    -X POST -u "admin:$PASSWORD" \
                    -H "Content-Type: application/json" \
                    --data @/tmp/$file \
                    $CENTRAL_URL$API
                  rm /tmp/$file
              done
              echo "Internal integrations updated."
          imagePullPolicy: Always
          name: updated-image-integration-creds
      dnsPolicy: ClusterFirst
      restartPolicy: Never
      serviceAccount: stackrox-image-integration-update-job
      serviceAccountName: stackrox-image-integration-update-job
      terminationGracePeriodSeconds: 30