name: gcp-artifact

on:
  push:
    branches:
      - main
  workflow_dispatch:

permissions:
  contents: read
  id-token: write

concurrency:
  group: gcp-artifact-${{ github.ref }}
  cancel-in-progress: true

env:
  PROJECT_ID: teleo-501523
  REGION: europe-west6
  ARTIFACT_REPOSITORY: teleo
  IMAGE_NAME: teleo-pipeline-gcp-staging
  WORKLOAD_IDENTITY_PROVIDER: projects/785938879453/locations/global/workloadIdentityPools/github-actions/providers/living-ip-github
  ARTIFACT_SERVICE_ACCOUNT: sa-artifact-builder@teleo-501523.iam.gserviceaccount.com

jobs:
  build-smoke-push:
    name: Build, smoke-run, and push Docker image
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v4

      - id: auth
        uses: google-github-actions/auth@v2
        with:
          workload_identity_provider: ${{ env.WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ env.ARTIFACT_SERVICE_ACCOUNT }}

      - uses: google-github-actions/setup-gcloud@v2

      - name: Configure Artifact Registry Docker auth
        run: |
          gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet

      - name: Build, smoke-run, and push
        shell: bash
        run: |
          set -euo pipefail
          tag="${GITHUB_SHA::7}"
          image_uri="${REGION}-docker.pkg.dev/${PROJECT_ID}/${ARTIFACT_REPOSITORY}/${IMAGE_NAME}:${tag}"
          image_digest="$(gcloud artifacts docker images describe "${image_uri}" --format='value(image_summary.digest)' 2>/dev/null || true)"

          if [[ -n "${image_digest}" ]]; then
            echo "Image tag already exists; reusing immutable Artifact Registry image."
            docker pull "${image_uri}@${image_digest}"
            docker run --rm "${image_uri}@${image_digest}"
          else
            docker build \
              -f Dockerfile.gcp-staging \
              --label "org.opencontainers.image.source=https://github.com/${GITHUB_REPOSITORY}" \
              --label "org.opencontainers.image.revision=${GITHUB_SHA}" \
              --label "livingip.revision=${GITHUB_SHA}" \
              --label "livingip.surface=teleo-infrastructure" \
              --label "livingip.tier=gcp-staging" \
              -t "${image_uri}" \
              .

            docker run --rm "${image_uri}"
            docker push "${image_uri}" | tee docker-push.log
            image_digest="$(awk '/digest: sha256:/ {print $3}' docker-push.log | tail -1)"
          fi
          test -n "${image_digest}"

          {
            echo "image_uri=${image_uri}"
            echo "image_digest=${image_digest}"
            echo "image_ref=${image_uri}@${image_digest}"
            echo "revision=${GITHUB_SHA}"
          } > gcp-artifact-image.txt

      - name: Upload image receipt
        uses: actions/upload-artifact@v4
        with:
          name: gcp-artifact-image
          path: gcp-artifact-image.txt
          if-no-files-found: error
