name: ci-build
run-name: Building ${{ github.ref_name }}
env:
  version: 1.12.0
permissions:
  contents: read
  packages: write
on:
  push:
    branches:
    - "**"
  pull_request:
jobs:
  lint:
    runs-on: ubuntu-24.04
    name: Run Hadolint
    steps:
      - uses: actions/checkout@v4
      - uses: hadolint/hadolint-action@v3.1.0
        with:
          dockerfile: Dockerfile
  docker:
    runs-on: ubuntu-24.04
    name: Build, Scan, and Push Docker Image
    needs:
    - lint

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

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

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

    - name: Extract metadata (tags, labels)
      id: meta
      uses: docker/metadata-action@v5
      with:
        images: ghcr.io/${{ github.repository }}
        tags: |
          type=raw,value=latest,enable={{is_default_branch}}
          type=raw,value=${{ env.version }}
          type=sha
        labels: |
          org.opencontainers.image.title=${{ github.repository }}
          org.opencontainers.image.version=${{ env.version }}
          org.opencontainers.image.source=${{ github.repositoryUrl }}
          org.opencontainers.image.created=${{ github.event.head_commit.timestamp }}

    - name: Build Docker image (no push)
      uses: docker/build-push-action@v5
      with:
        context: .
        push: false
        tags: ${{ steps.meta.outputs.tags }}
        labels: ${{ steps.meta.outputs.labels }}
        build-args: |
          MEDIAMTX_VERSION=${{ env.version }}
        load: true  # for Trivy
        cache-from: type=gha
        cache-to: type=gha,mode=max

    - name: Run Trivy vulnerability scanner
      uses: aquasecurity/trivy-action@0.28.0
      with:
        image-ref: ghcr.io/${{ github.repository }}:${{ env.version }}
        format: table
        exit-code: '1'
        severity: CRITICAL,HIGH

    - name: Push Docker image (if scan passed)
      if: success()
      uses: docker/build-push-action@v5
      with:
        context: .
        push: true
        tags: ${{ steps.meta.outputs.tags }}
        labels: ${{ steps.meta.outputs.labels }}
        provenance: true
        cache-from: type=gha
        cache-to: type=gha,mode=max