# Implantação em EC2 (Apache + Node + Systemd)

Guia de publicação do **Algar Venture Builder** em uma instância EC2 utilizando:

* Apache como reverse proxy HTTPS.
* Node.js SSR (TanStack Start/Nitro) executando via **systemd**.
* GitHub Actions para deploy automatizado.
* Usuário `deploy` responsável pela atualização da aplicação.
* Sem dependência de CDN externa em build ou runtime.

> **Gerenciador de pacotes:** utilizar somente `npm`.
> Não utilizar bun, yarn ou pnpm.

---

# 1. Visão geral da arquitetura

```text
Internet
   |
   v
Apache (80/443)
   |
   v
Node SSR (127.0.0.1:3002)
   |
   v
TanStack Start / Nitro node-server
```

Responsabilidades:

| Componente     | Responsabilidade                                       |
| -------------- | ------------------------------------------------------ |
| Apache         | TLS, gzip, cache de arquivos estáticos e proxy reverso |
| Node.js        | SSR da aplicação                                       |
| systemd        | Gerenciamento do processo Node                         |
| GitHub Actions | Pipeline de atualização                                |
| deploy         | Usuário responsável pelo deploy                        |

---

# 2. Usuário de deploy

A aplicação roda utilizando o usuário:

```text
deploy
```

O diretório da aplicação deve pertencer a esse usuário:

```bash
sudo chown -R deploy:deploy /var/www/html/algarventurebuilder/algar-venture
```

Validar:

```bash
ls -ld /var/www/html/algarventurebuilder/algar-venture
```

Esperado:

```text
deploy deploy
```

---

# 3. Fluxo de deploy

O deploy é iniciado automaticamente através do GitHub Actions quando ocorre push na branch:

```text
main
```

Fluxo:

```text
GitHub Push
     |
     v
GitHub Actions
     |
     v
Conecta VPN Pritunl
     |
     v
SSH para EC2 (usuário deploy)
     |
     v
Executa deploy.sh
     |
     +--> git fetch
     +--> git checkout main
     +--> git pull
     +--> npm ci
     +--> npm run build
     +--> systemctl restart
```

---

# 4. GitHub Actions

O workflow realiza:

## 4.1 Conexão VPN

A pipeline:

* instala OpenVPN;
* cria o perfil Pritunl através de secret;
* conecta no túnel privado;
* valida a interface `tun0`.

---

## 4.2 Conexão SSH

A execução ocorre utilizando:

```yaml
appleboy/ssh-action@v1.2.0
```

Usuário:

```text
deploy
```

Diretório:

```bash
/var/www/html/algarventurebuilder/algar-venture
```

Comando:

```bash
./deploy.sh
```

---

# 5. Script de deploy

Arquivo:

```text
deploy.sh
```

Responsável por:

1. Atualizar código.
2. Instalar dependências.
3. Gerar build.
4. Reiniciar serviço systemd.

Fluxo:

```bash
git fetch --all --prune

git checkout main

git pull --ff-only origin main

npm ci

npm run build

systemctl restart algarventurebuilder.service
```

---

# 6. Permissão do script

O script precisa ser executável:

```bash
chmod +x deploy.sh
```

Validar:

```bash
ls -l deploy.sh
```

Resultado esperado:

```text
-rwxr-xr-x deploy.sh
```

A permissão deve estar versionada no Git:

```bash
git update-index --chmod=+x deploy.sh
git commit -m "Define deploy.sh como executável"
git push
```

---

# 7. Serviço Systemd

A aplicação não utiliza PM2.

O processo Node é gerenciado pelo:

```text
algarventurebuilder.service
```

Exemplo:

```ini
[Service]

Type=simple

WorkingDirectory=/var/www/html/algarventurebuilder/algar-venture

EnvironmentFile=/var/www/html/algarventurebuilder/algar.env

ExecStart=/usr/bin/node .output/server/index.mjs

Restart=always
RestartSec=3

User=deploy
Group=deploy

StandardOutput=journal
StandardError=journal
```

---

## Aplicar alterações no serviço

Após alterar o arquivo:

```bash
sudo systemctl daemon-reload
```

Reiniciar:

```bash
sudo systemctl restart algarventurebuilder.service
```

Validar:

```bash
systemctl status algarventurebuilder.service
```

---

# 8. Permissões sudo do usuário deploy

O usuário `deploy` possui permissão somente para controlar o serviço necessário.

Arquivo:

```text
/etc/sudoers.d/deploy
```

Exemplo:

```text
deploy ALL=(root) NOPASSWD: \
/usr/bin/systemctl restart algarventurebuilder.service, \
/usr/bin/systemctl status algarventurebuilder.service, \
/usr/bin/systemctl daemon-reload
```

Validar:

```bash
sudo -l
```

---

# 9. Build Nitro node-server

O build gera:

```text
.output/server/index.mjs
```

Esse arquivo é o entrypoint executado pelo Node:

```bash
/usr/bin/node .output/server/index.mjs
```

A porta padrão da aplicação:

```text
127.0.0.1:3002
```

Validar:

```bash
ss -ltnp | grep node
```

Esperado:

```text
127.0.0.1:3002
```

---

# 10. Apache Reverse Proxy

Arquitetura:

```text
HTTPS
 |
 v
Apache :443
 |
 ProxyPass
 |
Node :3002
```

O Apache é responsável por:

* certificado SSL;
* redirecionamento HTTP → HTTPS;
* cache de assets;
* compressão.

---

# 11. Validação pós-deploy

## Serviço

```bash
systemctl status algarventurebuilder.service
```

## Processo Node

```bash
ps -ef | grep node
```

Esperado:

```text
deploy   node .output/server/index.mjs
```

## Porta

```bash
ss -ltnp | grep 3002
```

## Logs

```bash
journalctl -u algarventurebuilder.service -n 100 --no-pager
```

---

# 12. Troubleshooting

| Erro                                            | Causa                                      | Solução                                        |
| ----------------------------------------------- | ------------------------------------------ | ---------------------------------------------- |
| `Permission denied .git/FETCH_HEAD`             | Arquivos Git pertencem a outro usuário     | `chown -R deploy:deploy projeto`               |
| `insufficient permission for adding object`     | `.git/objects` com proprietário incorreto  | Corrigir ownership do repositório              |
| `deploy.sh Permission denied`                   | Script sem permissão de execução           | `chmod +x deploy.sh`                           |
| `systemctl Interactive authentication required` | Deploy tentando reiniciar sem sudo correto | Configurar `/etc/sudoers.d/deploy`             |
| `502 Bad Gateway`                               | Node parado ou porta errada                | Verificar `systemctl status` e logs            |
| Build falha                                     | Dependência ou código inválido             | Executar `npm ci && npm run build` manualmente |

---

# 13. Migração de processos antigos

Caso exista um processo Node antigo executando como `root`:

Identificar:

```bash
ps -ef | grep node
```

Verificar serviço:

```bash
systemctl show algarventurebuilder.service -p MainPID
```

Encerrar processo antigo:

```bash
kill <PID>
```

Subir novamente pelo systemd:

```bash
sudo systemctl restart algarventurebuilder.service
```

Validar:

```bash
ps -o pid,user,group,cmd -p $(systemctl show -p MainPID --value algarventurebuilder.service)
```

Resultado esperado:

```text
deploy deploy /usr/bin/node .output/server/index.mjs
```

---

# 14. Rollback

Caso seja necessário retornar uma versão:

```bash
cd /var/www/html/algarventurebuilder/algar-venture

git log --oneline -n 10

git reset --hard <commit>

npm ci

npm run build

sudo systemctl restart algarventurebuilder.service
```

---

# Checklist final

* [ ] Código atualizado via GitHub Actions.
* [ ] Repositório pertence ao usuário `deploy`.
* [ ] `deploy.sh` possui permissão de execução.
* [ ] Build gera `.output/server/index.mjs`.
* [ ] Serviço systemd executa como `deploy`.
* [ ] Node responde na porta 3002.
* [ ] Apache responde HTTPS.
* [ ] Logs sem erros no journal.
