name: Build and Deploy

on:
  push:
    branches: [ main ]

jobs:
  build-and-push:
    runs-on: self-hosted
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout code
        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: Build and push Manager
        uses: docker/build-push-action@v5
        with:
          context: ./manager
          push: true
          # Constrói nativamente apenas para ARM64 na Oracle
          platforms: linux/arm64
          tags: ghcr.io/${{ github.repository }}/edumanager:latest

      - name: Build and push Portal
        uses: docker/build-push-action@v5
        with:
          context: ./portal
          push: true
          # Constrói nativamente apenas para ARM64 na Oracle
          platforms: linux/arm64
          tags: ghcr.io/${{ github.repository }}/portalaluno:latest

      - name: Atualizar Containers em Produção (Watchtower)
        run: |
          # Cria um arquivo de autenticacao do Docker manual (A prova de bloqueios de permissão)
          AUTH=$(echo -n "${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}" | base64 -w 0)
          echo "{\"auths\": {\"ghcr.io\": {\"auth\": \"$AUTH\"}}}" > $(pwd)/ghcr-config.json
          
          docker run --rm \
            -e DOCKER_API_VERSION=1.44 \
            -v /var/run/docker.sock:/var/run/docker.sock \
            -v $(pwd)/ghcr-config.json:/config.json \
            containrrr/watchtower \
            --run-once --cleanup --debug
