name: Test, Build and Publish

on:
  push:
    branches:
      - main
    tags:
      - '*'
  pull_request:
  workflow_dispatch:

env:
  # Use the github container registry
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

  
jobs:

  # Run the tests scripts
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: 3.11
        cache: pip
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        python -m pip install -r requirements.txt
    - name: Run tests
      run: |
        python tests/test.py

  # Build and push the docker images
  build-and-push-images:
    runs-on: ubuntu-latest
    needs: test
    
    permissions:
      contents: read
      packages: write
      attestations: write
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
     
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
        with:
          platforms: arm32v7/armhf # arm64v8/aarch64 - no current need for arm64

      - name: Log in to the Container registry
        uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # Use docker-container driver for multi-platform builds
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
        with:
          driver: docker-container  

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=tag
            type=ref,event=branch
            type=ref,event=pr
            type=edge,branch=main

      - name: Build and push Docker image
        id: push
        uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
        with:
          context: .
          platforms: linux/arm/v7,linux/amd64 # linux/arm64 no current need for arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          # Cache to help the step run a little faster
          cache-from: type=gha
          cache-to: type=gha,mode=max
      
      - name: Generate artifact attestation
        uses: actions/attest-build-provenance@v1
        with:
          subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
          subject-digest: ${{ steps.push.outputs.digest }}
          push-to-registry: true