name: Build and Deploy (Gitea)

on:
  push:
    branches: [ main ]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Build Manager
        run: |
          cd manager
          docker build --no-cache -t edumanager:local .
          
      - name: Build Portal
        run: |
          cd portal
          docker build --no-cache -t portalaluno:local .

      - name: Deploy to Portainer
        run: |
          docker service update --force --image edumanager:local edumanager-v2_edumanager
          docker service update --force --image portalaluno:local edumanager-v2_portalaluno

      - name: Autorizar Chave SSH da VPS
        run: |
          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 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 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
          '
