name: 'Docker Bazel Run'
description: 'Run a Bazel-based docker image for Protobuf CI testing'
inputs:
  credentials:
    required: true
    description: "The GCP credentials to use for reading the docker image"
    type: string
  image:
    required: false
    default: us-docker.pkg.dev/protobuf-build/containers/common/linux/bazel:5.1.1-aec4d74f2eb6938fc53ef7d9a79a4bf2da24abc1
    description: "The docker image to use"
    type: string
  bazel-cache:
    required: true
    description: >
      A unique path for the Bazel cache.  This will trigger the generation
      of a BAZEL_CACHE environment variable inside the container that provides
      the appropriate flags for any bazel command.
    type: string
  bazel:
    required: false
    description: "The Bazel command to run"
    type: string
  bash:
    required: false
    description: "A bash command to run.  $BAZEL_FLAGS will be available to use for bazel runs."
    type: string

runs:
  using: 'composite'
  steps:
    - name: Authenticate
      id: auth
      uses: ./.github/actions/internal/gcloud-auth
      with:
        credentials: ${{ inputs.credentials }}

    - name: Setup Runner
      uses: ./.github/actions/internal/setup-runner

    - name: Setup Bazel
      id: bazel
      uses: ./.github/actions/internal/bazel-setup
      with:
        credentials-file: /workspace/$(basename ${{ steps.auth.outputs.credentials-file }})
        bazel-cache: ${{ inputs.bazel-cache }}

    - name: Hook up repository Cache
      shell: bash
      run: echo "BAZEL_FLAGS=$BAZEL_FLAGS --repository_cache='/workspace/${{ env.REPOSITORY_CACHE_PATH }}'" >> $GITHUB_ENV

    - name: Validate inputs
      if: ${{ (inputs.bash && inputs.bazel) || (!inputs.bash && !inputs.bazel) }}
      shell: bash
      run: echo "Invalid specification of both non-Bazel and Bazel command"; exit 1

    - name: Run Bash Docker
      uses: ./.github/actions/internal/docker-run
      if: ${{ inputs.bash }}
      with:
        image: ${{ inputs.image }}
        run-flags: --entrypoint "/bin/bash"
        command: -l -c "${{ inputs.bash }}"

    - name: Run Bazel Docker
      uses: ./.github/actions/internal/docker-run
      if: ${{ !inputs.bash }}
      with:
        image: ${{ inputs.image }}
        command: ${{ inputs.bazel }} ${{ env.BAZEL_FLAGS }}

    - name: Save Bazel repository cache
      # Only allow repository cache updates during post-submits.
      if: ${{ github.event_name != 'pull_request' && github.event_name != 'pull_request_target' }}
      uses: ./.github/actions/internal/repository-cache-save
