apiVersion: tekton.dev/v1alpha1
kind: Task
metadata:
  name: publish-tekton-triggers
spec:
  inputs:
    resources:
    - name: source
      type: git
      targetPath: go/src/github.com/tektoncd/triggers
    - name: bucket
      type: storage
    params:
    - name: versionTag
      description: The vX.Y.Z version that the artifacts should be tagged with (including `v`)
    - name: imageRegistry
      description: TODO(tektoncd/pipeline#569) This is a hack to make it easy for folks to switch the registry being used by the many many image outputs
    - name: pathToProject
      description: The path to the folder in the go/src dir that contains the project, which is used by `ko` to name the resulting images
    - name: releaseAsLatest
      description: "Whether to tag and publish this release as Triggers' latest"
      default: "true"
  outputs:
    resources:
    - name: bucket
      type: storage
    - name: builtControllerImage
      type: image
    - name: builtWebhookImage
      type: image
    - name: builtEventListenerSinkImage
      type: image
    - name: notification
      type: cloudEvent
  steps:
  - name: link-input-bucket-to-output
    image: busybox
    command: ["cp"]
    args:
    - -r
    - "/workspace/bucket"
    - "/workspace/output/"

  - name: ensure-release-dirs-exist
    image: busybox
    command: ["mkdir"]
    args:
    - "-p"
    - "/workspace/output/bucket/latest/"
    - "/workspace/output/bucket/previous/$(inputs.params.versionTag)/"

  - name: run-ko
    image: gcr.io/tekton-releases/dogfooding/ko-gcloud:latest
    env:
    - name: KO_DOCKER_REPO
      value: $(inputs.params.imageRegistry)
    - name: GOPATH
      value: /workspace/go
    - name: CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE
      value: /secret/release.json
    script: |
      #!/bin/sh
      set -ex

      # Auth with CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE
      gcloud auth configure-docker

      # ko requires this variable to be set in order to set image creation timestamps correctly https://github.com/google/go-containerregistry/pull/146
      export SOURCE_DATE_EPOCH=`date +%s`

      # Change to directory with our .ko.yaml
      cd /workspace/go/src/github.com/tektoncd/triggers
      # Rewrite "devel" to inputs.params.versionTag
      sed -i -e 's/\(triggers.tekton.dev\/release\): "devel"/\1: "$(inputs.params.versionTag)"/g' -e 's/\(version\): "devel"/\1: "$(inputs.params.versionTag)"/g' /workspace/go/src/github.com/tektoncd/triggers/config/*.yaml

      OUTPUT_BUCKET_RELEASE_DIR="/workspace/output/bucket/previous/$(inputs.params.versionTag)"

      # Publish images and create release.yaml
      ko resolve --preserve-import-paths -t $(inputs.params.versionTag) -f /workspace/go/src/github.com/tektoncd/triggers/config/ > $OUTPUT_BUCKET_RELEASE_DIR/release.yaml

      # Publish images and create release.notags.yaml
      # This is useful if your container runtime doesn't support the `image-reference:tag@digest` notation
      # This is currently the case for `cri-o` (and most likely others)
      ko resolve --preserve-import-paths -f /workspace/go/src/github.com/tektoncd/triggers/config/ > $OUTPUT_BUCKET_RELEASE_DIR/release.notags.yaml
    volumeMounts:
      - name: gcp-secret
        mountPath: /secret

  - name: copy-to-latest-bucket
    image: busybox
    workingDir: "/workspace/output/bucket"
    script: |
      #!/bin/sh
      set -ex

      if [[ "$(inputs.params.releaseAsLatest)" == "true" ]]
      then
        mkdir -p "/workspace/output/bucket/latest/"
        OUTPUT_BUCKET_RELEASE_DIR="/workspace/output/bucket/previous/$(inputs.params.versionTag)"
        OUTPUT_BUCKET_LATEST_DIR="/workspace/output/bucket/latest"
        cp "$OUTPUT_BUCKET_RELEASE_DIR/release.yaml" "$OUTPUT_BUCKET_LATEST_DIR/release.yaml"
        cp "$OUTPUT_BUCKET_RELEASE_DIR/release.notags.yaml" "$OUTPUT_BUCKET_LATEST_DIR/release.notags.yaml"
      fi

  - name: tag-images
    image: google/cloud-sdk
    script: |
      #!/usr/bin/env bash
      set -ex

      REGIONS=(us eu asia)
      IMAGES=(
        $(inputs.params.imageRegistry)/$(inputs.params.pathToProject)/$(outputs.resources.builtControllerImage.url)
        $(inputs.params.imageRegistry)/$(inputs.params.pathToProject)/$(outputs.resources.builtWebhookImage.url)
        $(inputs.params.imageRegistry)/$(inputs.params.pathToProject)/$(outputs.resources.builtEventListenerSinkImage.url)
      )
      # Parse the built images from the release.yaml generated by ko
      BUILT_IMAGES=( $(/workspace/go/src/github.com/tektoncd/triggers/tekton/koparse/koparse.py --path /workspace/output/bucket/latest/release.yaml --base $(inputs.params.imageRegistry)/$(inputs.params.pathToProject) --images ${IMAGES[@]}) )

      # Auth with account credentials
      gcloud auth activate-service-account --key-file=/secret/release.json

      # Tag the images and put them in all the regions
      for IMAGE in "${BUILT_IMAGES[@]}"
      do
        IMAGE_WITHOUT_SHA=${IMAGE%%@*}
        IMAGE_WITHOUT_SHA_AND_TAG=${IMAGE_WITHOUT_SHA%%:*}
        IMAGE_WITH_SHA=${IMAGE_WITHOUT_SHA_AND_TAG}@${IMAGE##*@}
        if [[ "$(inputs.params.releaseAsLatest)" == "true" ]]
        then
          gcloud -q container images add-tag ${IMAGE_WITH_SHA} ${IMAGE_WITHOUT_SHA_AND_TAG}:latest
        fi
        for REGION in "${REGIONS[@]}"
        do
          if [[ "$(inputs.params.releaseAsLatest)" == "true" ]]
          then
            for TAG in "latest" $(inputs.params.versionTag)
            do
              gcloud -q container images add-tag ${IMAGE_WITH_SHA} ${REGION}.${IMAGE_WITHOUT_SHA_AND_TAG}:$TAG
            done
          else
            TAG="$(inputs.params.versionTag)"
            gcloud -q container images add-tag ${IMAGE_WITH_SHA} ${REGION}.${IMAGE_WITHOUT_SHA_AND_TAG}:$TAG
          fi
        done
      done
    volumeMounts:
      - name: gcp-secret
        mountPath: /secret

  volumes:
    - name: gcp-secret
      secret:
        secretName: release-secret
