name: Build and Publish Container

on:
  workflow_run:
    workflows: ["CLI Smoke Tests", "Generate Baselines and Increment Build"]
    types: [completed]
    branches: [main, dev_27]
  workflow_dispatch:

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository_owner }}/mscp_2.0

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    # On the primary repo: trigger after Generate Baselines completes on a real (non-bump) commit.
    # On forks: trigger after CLI Smoke Tests completes (Generate Baselines is a no-op there).
    if: >
      github.event_name == 'workflow_dispatch' ||
      (github.event.workflow_run.conclusion == 'success' && (
        (github.event.workflow_run.name == 'Generate Baselines and Increment Build' &&
         github.repository == 'usnistgov/macos_security' &&
         !contains(github.event.workflow_run.head_commit.message, '[skip ci]')) ||
        (github.event.workflow_run.name == 'CLI Smoke Tests' &&
         github.repository != 'usnistgov/macos_security')
      ))

    permissions:
      contents: read
      packages: write
      id-token: write   # required for cosign keyless signing via OIDC
      attestations: write
      actions: read     # required to query workflow run status

    steps:
      - name: Verify lint passed
        if: github.event_name != 'workflow_dispatch' && github.event.workflow_run.name == 'CLI Smoke Tests'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SHA: ${{ github.event.workflow_run.head_sha }}
        run: |
          repo="${{ github.repository }}"
          wf_id=$(gh api "repos/$repo/actions/workflows" --jq '.workflows[] | select(.name == "Lint Code Base") | .id')
          result=$(gh api "repos/$repo/actions/workflows/$wf_id/runs?head_sha=$SHA&per_page=1" --jq '.workflow_runs[0].conclusion // empty')
          if [[ "$result" != "success" ]]; then
            echo "Lint Code Base did not pass (conclusion: ${result:-not found})"
            exit 1
          fi

      - name: Checkout repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0  # v7
        with:
          ref: ${{ github.event.workflow_run.head_sha || github.sha }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8  # v4.2.0

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5  # v4.1.0

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee  # v4.2.0
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Determine source branch
        id: branch
        env:
          HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
        run: |
          branch="${HEAD_BRANCH:-${{ github.ref_name }}}"
          echo "branch=${branch}" >> "$GITHUB_OUTPUT"
          if [[ "${branch}" == "main" ]]; then
            echo "is_main=true" >> "$GITHUB_OUTPUT"
            echo "image_tag=latest" >> "$GITHUB_OUTPUT"
          else
            echo "is_main=false" >> "$GITHUB_OUTPUT"
            echo "image_tag=${branch}" >> "$GITHUB_OUTPUT"
          fi

      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9  # v6.1.0
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=raw,value=main,enable=${{ steps.branch.outputs.is_main == 'true' }}
            type=raw,value=latest,enable=${{ steps.branch.outputs.is_main == 'true' }}
            type=raw,value=${{ steps.branch.outputs.branch }},enable=${{ steps.branch.outputs.is_main != 'true' }}
            type=sha,prefix=sha-,format=short

      - name: Build and push Docker image
        id: build-push
        uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a  # v7.3.0
        with:
          context: .
          file: .github/container/Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: |
            ${{ steps.meta.outputs.labels }}
            org.opencontainers.image.revision=${{ github.event.workflow_run.head_sha || github.sha }}
          build-args: |
            BUILD_SHA=${{ github.event.workflow_run.head_sha || github.sha }}
            IMAGE_REPO=${{ github.repository }}
            IMAGE_TAG=${{ steps.branch.outputs.image_tag }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Install cosign
        uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6  # v4.1.2

      - name: Sign image with cosign (keyless via GitHub OIDC)
        env:
          DIGEST: ${{ steps.build-push.outputs.digest }}
          TAGS: ${{ steps.meta.outputs.tags }}
          COSIGN_REGISTRY_USERNAME: ${{ github.actor }}
          COSIGN_REGISTRY_PASSWORD: ${{ secrets.GITHUB_TOKEN }}
        run: |
          images=""
          for tag in ${TAGS}; do
            images+="${tag}@${DIGEST} "
          done
          cosign sign --yes ${images}

      - name: Generate build provenance attestation
        uses: actions/attest@a1948c3f048ba23858d222213b7c278aabede763  # v4.1.1
        with:
          subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          subject-digest: ${{ steps.build-push.outputs.digest }}
          push-to-registry: true
