name: CI/CD Pipeline

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

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

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.22'
          
      - name: Install dependencies
        run: go mod download
        
      - name: Run tests
        run: go test -v ./...
        
      - name: Run linter
        uses: golangci/golangci-lint-action@v3
        with:
          version: latest

  build:
    needs: test
    runs-on: ubuntu-latest
    strategy:
      matrix:
        component: [operator, portal, mom]
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v3
      
      - name: Install Podman
        run: |
          sudo apt-get update
          sudo apt-get install -y podman
          
      - name: Login to GitHub Container Registry
        run: |
          echo "${{ secrets.GITHUB_TOKEN }}" | podman login ghcr.io -u ${{ github.actor }} --password-stdin
          
      - name: Build and push
        run: |
          COMPONENT=${{ matrix.component }}
          if [ "$COMPONENT" = "mom" ]; then
            COMPONENT="api"
          fi
          podman build -t ${{ env.REGISTRY }}/${{ env.OWNER }}/container-mom-${COMPONENT}:${{ github.sha }} -f build/Dockerfile.${{ matrix.component }} .
          podman tag ${{ env.REGISTRY }}/${{ env.OWNER }}/container-mom-${COMPONENT}:${{ github.sha }} ${{ env.REGISTRY }}/${{ env.OWNER }}/container-mom-${COMPONENT}:latest
          if [ "${{ github.event_name }}" != "pull_request" ]; then
            podman push ${{ env.REGISTRY }}/${{ env.OWNER }}/container-mom-${COMPONENT}:${{ github.sha }}
            podman push ${{ env.REGISTRY }}/${{ env.OWNER }}/container-mom-${COMPONENT}:latest
          fi
