name: "Build and push GARM images"
on:
  workflow_call:
    inputs:
      push_to_project:
        description: "Project to build images for"
        required: false
        type: string
        default: "ghcr.io/cloudbase"
      ref:
        description: "Ref to build"
        required: false
        type: string
        default: "main"

permissions:
  contents: read

jobs:
    images:
      permissions:
        packages: write
      name: "Build GARM images"
      runs-on: ubuntu-latest
      steps:
        - name: "Checkout"
          uses: actions/checkout@v4
          with:
            path: src/github.com/cloudbase/garm
            fetch-depth: 0

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

        - name: Login to GitHub Container Registry
          uses: docker/login-action@v2
          with:
            registry: ghcr.io
            username: ${{ github.actor }}
            password: ${{ secrets.GITHUB_TOKEN }}

        - name: Build and push image
          env:
            IMAGE_REGISTRY: ${{ inputs.push_to_project }}
            GH_REF: ${{ inputs.ref }}
          working-directory: src/github.com/cloudbase/garm
          run: |
            if [ "$GH_REF" == "main" ]; then
              IMAGE_TAG="nightly"
            else
              IMAGE_TAG=$(git describe --tags --match='v[0-9]*' --always ${GH_REF})
            fi
            docker buildx build \
              --provenance=false \
              --platform linux/amd64,linux/arm64 \
              --label "org.opencontainers.image.source=https://github.com/cloudbase/garm/tree/${GH_REF}" \
              --label "org.opencontainers.image.description=GARM ${GH_REF}" \
              --label "org.opencontainers.image.licenses=Apache 2.0" \
              --build-arg="GARM_REF=${GH_REF}" \
              -t ${IMAGE_REGISTRY}/garm:"${IMAGE_TAG}" \
              --push .
