name: Build and Push Container Images

on:
  push:
    branches:
      - main
    tags:
      - "v*"
  pull_request:
    branches:
      - main

env:
  REGISTRY: ghcr.io
  OWNER: ${{ github.repository_owner }}

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    strategy:
      matrix:
        service:
          - name: web-portal
            context: src
            dockerfile: web-portal/Dockerfile
          - name: billing-service
            context: src
            dockerfile: billing-service/Dockerfile
          - name: metrics-service
            context: src
            dockerfile: metrics-service/Dockerfile
          - name: dns-manager
            context: src
            dockerfile: dns-manager/Dockerfile

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Log in to GitHub Container Registry
        if: github.event_name != 'pull_request'
        uses: redhat-actions/podman-login@v1
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.OWNER }}/container-mom-${{ matrix.service.name }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=sha,format=long
            type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}

      - name: Copy shared files
        run: |
          for service in web-portal billing-service metrics-service dns-manager; do
            mkdir -p src/$service/src
            cp src/*.cr src/$service/src/
          done

      - name: Build images
        uses: redhat-actions/buildah-build@v2
        with:
          image: container-mom-${{ matrix.service.name }}
          tags: ${{ steps.meta.outputs.tags }}
          containerfiles: src/${{ matrix.service.name }}/Dockerfile
          context: src/${{ matrix.service.name }}
          extra-args: |
            --format=docker
            --layers=true
            --storage-driver=vfs

      - name: Push to registry
        if: github.event_name != 'pull_request'
        uses: redhat-actions/push-to-registry@v2
        with:
          image: container-mom-${{ matrix.service.name }}
          tags: ${{ steps.meta.outputs.tags }}
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
