name: Build and Push Container Images

on:
  push:
    branches:
      - main
    paths-ignore:
      - '**.md'
      - 'docs/**'
      - 'charts/**'
  release:
    types: [published]

env:
  KO_DOCKER_REPO: ghcr.io/${{ github.repository }}/controller

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.24'
          cache: true

      - name: Install ko
        uses: ko-build/setup-ko@v0.6

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to ghcr.io
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Set image tags
        id: tags
        run: |
          if [[ "${{ github.ref }}" == refs/tags/* ]]; then
            echo "tags=${{ github.ref_name }}" >> $GITHUB_OUTPUT
          else
            echo "tags=latest" >> $GITHUB_OUTPUT
          fi

      - name: Build and push multi-arch images
        env:
          GOFLAGS: "-ldflags=-X=main.version=${{ steps.tags.outputs.tags }}"
        run: |
          # Build and push multi-arch images
          ko build \
            --platform=linux/amd64,linux/arm64 \
            --bare \
            --tags=${{ steps.tags.outputs.tags }} \
            ./cmd/controller

          # Verify the manifest
          docker buildx imagetools inspect $KO_DOCKER_REPO:${{ steps.tags.outputs.tags }}
