name: CI/CD Pipeline para YTExtractor

on:
  push:
    branches: [ main, 'release/*' ]
  pull_request:
    branches: [ main, 'release/*' ]

jobs:
  build:
    runs-on: ubuntu-22.04
    
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup .NET
        uses: actions/setup-dotnet@v3
        with:
          dotnet-version: '8.0.x'
          
      - name: Restore dependencies
        run: dotnet restore
        
      - name: Build
        run: dotnet build --no-restore
        
      - name: Test
        run: dotnet test --no-build --verbosity normal
        
      - name: Build Docker image
        uses: docker/build-push-action@v4
        with:
          context: .
          push: false
          load: true
          tags: ytextractor:${{ github.sha }}
          platforms: linux/amd64,linux/arm64
          
      - name: Save Docker image
        run: docker save ytextractor:${{ github.sha }} > ytextractor-image.tar
          
      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: docker-image
          path: ytextractor-image.tar
  
  deploy-localACDC:
    needs: build
    runs-on: ubuntu-22.04
    if: github.ref == 'refs/heads/main'
    
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: docker-image
          
      - name: Deploy to localACDC
        run: |
          echo "Implantando no servidor localACDC"
          scp ytextractor-image.tar user@localACDC:/tmp/
          ssh user@localACDC "docker load < /tmp/ytextractor-image.tar && \
                             docker stop ytextractor || true && \
                             docker rm ytextractor || true && \
                             docker run -d --name ytextractor -p 80:80 ytextractor:${{ github.sha }}"
  
  deploy-pi2Zero:
    needs: build
    runs-on: ubuntu-22.04
    if: startsWith(github.ref, 'refs/heads/release/')
    
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: docker-image
          
      - name: Deploy to pi2Zero (Orange Pi Zero)
        run: |
          echo "Implantando no Orange Pi Zero (recursos limitados)"
          # Transfere a imagem para o servidor
          scp ytextractor-image.tar user@pi2Zero:/tmp/
          
          # Comandos específicos para o Orange Pi Zero (otimizados para baixa memória)
          ssh user@pi2Zero "
            # Limpar recursos não utilizados
            docker system prune -f
            
            # Parar e remover contêiner existente
            docker stop ytextractor || true
            docker rm ytextractor || true
            
            # Carregar a nova imagem
            docker load < /tmp/ytextractor-image.tar
            
            # Iniciar o serviço com limites de memória
            docker run -d --name ytextractor -p 80:80 --memory=300m --memory-swap=600m ytextractor:${{ github.sha }}
          "
