name: Build and Deploy

on:
  push:
    branches: [ main ]
  workflow_dispatch: {}

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

      - name: Autorizar Chave SSH da VPS
        run: |
          # Como o runner executa dentro de um container Docker isolado, usamos o docker daemon
          # do host para rodar um container temporário e gravar a chave nos usuários e root da VPS.
          docker run --rm -v /home:/host-home -v /root:/host-root alpine sh -c '
            KEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDvJM3XAD2M8h23iwYDcolLtrjFdwUCrD30N2457yOnbJ79rj7FC0aIGBExqXE62V640qzR4TzI/FgRVhMwcvDD6WvGlHDppdqjABwt5U19ffO+a56fAcWr33kRkHh7sFnNqLasZ58j+fAqWUnYm/K5bD+5ionK6Hqp4hirZyh5pjeC0/+ast84MLUOx4jrIbeJcAXSCug61vv34E7hXERD/MOmwlQx4AZlfLWX3r6JKU80frdpmQHowQ4H6h4EBC8J0u19uYi97pLlwqUqcpK+MB/UYNMrkIt7KUcLyq0uGdxV777AdlyUw7MGpHPX3zy39lqSeFiiQb6MuE+Y0RvLOGNeNQUuGd8YK5W7e+ZZ09lo04hUF8r43I8QRDLyaAz71G4nVZFslm2RSEc/dk7cr5yUq/dgmcLvzNgEYjJ4lkefjaJmZir1S7sj9tbE+AshmqBUlxOaKxEKX+grAc0Jr4qrG0R+AD83LlnjlxjuFXe4MOr495AjlR8hIodx5EwirTIvNRMwDHSRAQM04MTJ1tm5tZ6iEFsBCNE92f+CZfEQ3SbBKku++rNOmjHzTELRY83IDghv3N3tKtw3HL6L6gUG5moGOqV91UH+nhElZAR1XOoDwbYM6d/L2lM1AQBc4vNcKyDN1ryAaZU4zFc6p56xlBEaEHmPmYK+qMmmsQ== sidney@DESKTOP-DMF9AJU"
            
            echo "=== Diretorios Home no Host ==="
            ls -la /host-home
            
            for u in ubuntu opc admin sidney debian; do
              if [ -d "/host-home/$u" ]; then
                echo "Cadastrando chave para o usuario: $u"
                mkdir -p "/host-home/$u/.ssh"
                echo "$KEY" >> "/host-home/$u/.ssh/authorized_keys"
                chmod 700 "/host-home/$u/.ssh"
                chmod 600 "/host-home/$u/.ssh/authorized_keys"
                UID_GID=$(stat -c "%u:%g" "/host-home/$u")
                chown -R $UID_GID "/host-home/$u/.ssh"
              fi
            done
            
            echo "Cadastrando chave para o usuario: root"
            mkdir -p /host-root/.ssh
            echo "$KEY" >> /host-root/.ssh/authorized_keys
            chmod 700 /host-root/.ssh
            chmod 600 /host-root/.ssh/authorized_keys
          '

