name: Deploy ASP.NET MVC to OCI

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

jobs:
  build-and-deploy:
    runs-on: localACDC
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      
    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3

    - name: Cache Docker layers
      uses: actions/cache@v3
      with:
        path: /tmp/.buildx-cache
        key: ${{ runner.os }}-buildx-${{ github.sha }}
        restore-keys: |
          ${{ runner.os }}-buildx-

    - name: Debug - List files
      run: |
        echo "=== Arquivos na raiz ==="
        ls -la
        echo "=== Procurando Dockerfile ==="
        find . -name "Dockerfile" -o -name "dockerfile" -type f
        echo "=== Estrutura do projeto ==="
        tree -L 3 || find . -type d -name "OnlyOneAccessTemplate"
        
    - name: Build and push Docker image
      uses: docker/build-push-action@v5
      with:
        context: .
        file: ./Dockerfile
        platforms: linux/arm64
        push: true
        tags: |
          registry.redecarneir.us/onlyoneaccesstemplate:latest
          registry.redecarneir.us/onlyoneaccesstemplate:${{ github.sha }}
        cache-from: |
          type=local,src=/tmp/.buildx-cache
          type=registry,ref=registry.redecarneir.us/onlyoneaccesstemplate:cache
        cache-to: |
          type=local,dest=/tmp/.buildx-cache-new,mode=max
          type=registry,ref=registry.redecarneir.us/onlyoneaccesstemplate:cache,mode=max
        build-args: |
          BUILDKIT_INLINE_CACHE=1
          
    - name: Move cache
      run: |
        rm -rf /tmp/.buildx-cache
        mv /tmp/.buildx-cache-new /tmp/.buildx-cache
        
    - name: Deploy to OCI Server
      uses: appleboy/ssh-action@v1.0.3
      with:
        host: 129.146.116.218
        username: ${{ secrets.SSH_USERNAME }}
        key: ${{ secrets.SSH_PRIVATE_KEY }}
        port: 22
        timeout: 60s
        script: |
          # Para qualquer container que esteja usando a porta 80
          echo "=== Verificando containers na porta 80 ==="
          CONTAINERS_PORT_80=$(docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Ports}}" | grep ':80->' | awk '{print $2}' || true)
          if [ ! -z "$CONTAINERS_PORT_80" ]; then
            echo "Parando containers na porta 80: $CONTAINERS_PORT_80"
            echo "$CONTAINERS_PORT_80" | xargs -r docker stop
            echo "$CONTAINERS_PORT_80" | xargs -r docker rm
          else
            echo "Nenhum container encontrado na porta 80"
          fi
          
          # Para o container anterior da aplicação (se existir)
          docker stop onlyoneaccesstemplate || true
          docker rm onlyoneaccesstemplate || true
          
          # Remove imagem antiga
          docker rmi registry.redecarneir.us/onlyoneaccesstemplate:latest || true
          
          # Puxa nova imagem
          docker pull registry.redecarneir.us/onlyoneaccesstemplate:latest
          
          # Executa o novo container na porta 80
          # docker run -d \
          #   --name onlyoneaccesstemplate \
          #   --restart unless-stopped \
          #   -p 80:8080 \
          #   -p 443:8081 \
          #   -e ASPNETCORE_ENVIRONMENT=Production \
          #   -e ASPNETCORE_URLS="http://+:8080;https://+:8081" \
          #   registry.redecarneir.us/onlyoneaccesstemplate:latest
          docker run -d \
              --name onlyoneaccesstemplate \
              --restart unless-stopped \
              -p 80:8080 \
              -p 443:8081 \
              --memory=2g \
              --cpus=1.5 \
              --health-cmd="curl -f http://localhost:8080/health || exit 1" \
              --health-interval=30s \
              --health-timeout=10s \
              --health-retries=3 \
              --health-start-period=60s \
              -e ASPNETCORE_ENVIRONMENT=Production \
              -e ASPNETCORE_URLS="http://+:8080;https://+:8081" \
              -e DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true \
              -e DOTNET_USE_POLLING_FILE_WATCHER=true \
              -e DOTNET_EnableDiagnostics=0 \
              -e DOTNET_RUNNING_IN_CONTAINER=true \
              registry.redecarneir.us/onlyoneaccesstemplate:latest
  
          # Limpa imagens não utilizadas
          docker image prune -f
          
          # Verifica se o container está rodando
          docker ps | grep onlyoneaccesstemplate
          
          # Testa se a aplicação está respondendo na porta 80
          sleep 10
          curl -f http://localhost:80 || echo "Aplicação pode estar inicializando..."

    - name: Verify deployment
      uses: appleboy/ssh-action@v1.0.3
      with:
        host: 129.146.116.218
        username: ${{ secrets.SSH_USERNAME }}
        key: ${{ secrets.SSH_PRIVATE_KEY }}
        port: 22
        script: |
          echo "=== Status dos containers ==="
          docker ps -a | grep onlyoneaccesstemplate
          
          echo "=== Logs da aplicação (últimas 20 linhas) ==="
          docker logs onlyoneaccesstemplate --tail 20
          
          echo "=== Teste de conectividade ==="
          curl -I http://localhost:80 || echo "Aplicação ainda não está acessível"