name: Build and publish containerization test images

permissions:
  contents: read

on: 
  workflow_dispatch: 
    inputs: 
      publish: 
        type: boolean
        description: "Publish the built image"
        default: false
      version: 
        type: string
        description: "Version of the image to create"
        default: "test"
      image:
        type: choice
        description: Test image to build
        options:
          - dockermanifestimage
          - emptyimage
        default: 'dockermanifestimage'
      useBuildx:
        type: boolean
        description: "Use docker buildx to build the image"
        default: false

jobs: 
  image: 
    name: Build test images
    timeout-minutes: 30
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write 
    steps:
      - name: Check branch
        env:
          GH_REF: ${{ github.ref }}
          PUBLISH: ${{ inputs.publish }}
        run: |
          if [[ "${GH_REF}" != "refs/heads/main" ]] && [[ "${GH_REF}" != refs/heads/release* ]] && [[ "${PUBLISH}" == "true" ]]; then
            echo "❌ Cannot publish an image if we are not on main or a release branch."
            exit 1
          fi
      - name: Check inputs
        env:
          IMAGE: ${{ inputs.image }}
          USE_BUILDX: ${{ inputs.useBuildx }}
        run: |
          if [[ "${IMAGE}" == "dockermanifestimage" ]] && [[ "${USE_BUILDX}" == "true" ]]; then
            echo "❌ dockermanifestimage cannot be built with buildx"
            exit 1
          fi

          if [[ "${IMAGE}" == "emptyimage" ]] && [[ "${USE_BUILDX}" != "true" ]]; then
            echo "❌ emptyimage should be built with buildx"
            exit 1
          fi
      - name: Checkout repository
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8  # v6 
      - name: Login to GitHub Container Registry
        uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9  # v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Set up Docker Buildx
        if: ${{ inputs.useBuildx }} 
        uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f  # v3
      - name: Build dockerfile and push image
        uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8  # v6
        with:
          push: ${{ inputs.publish }}
          context: Tests/TestImages/${{ inputs.image }}
          tags: ghcr.io/apple/containerization/${{ inputs.image }}:${{ inputs.version }}
