diff --git a/.gitignore b/.gitignore index ce38f3b..fd73a93 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ composer.lock it-toolbox-report-*.txt it-toolbox-report-*.md it-toolbox-report-*.json +it-toolbox-inventory-*.md +it-toolbox-inventory-*.json .DS_Store Thumbs.db .env diff --git a/README.md b/README.md index 6d3bd39..47b1ab5 100644 --- a/README.md +++ b/README.md @@ -11,58 +11,75 @@ ## Overview -**IT Toolbox CLI (`it-toolbox`)** is a cross-platform, interactive terminal utility (TUI/CLI) built with **PHP 8.3+**, **Laravel Zero**, and **Laravel Prompts**. Designed for **IT Support Technicians, Help Desk Engineers, and System Administrators**, it unifies daily troubleshooting, hardware/OS diagnostics, print spooler recovery, network health checks, and safe temporary file cleanup across both **Windows** and **Linux** (distribution-agnostic) environments from a single portable binary. +**IT Toolbox CLI (`it-toolbox`)** is a cross-platform, interactive terminal utility (TUI/CLI) built with **PHP 8.3+**, **Laravel Zero**, and **Laravel Prompts**. Designed for **IT Support Technicians, Help Desk Engineers, and System Administrators**, it unifies **35+ diagnostic, maintenance, security, printer, network, and asset inventory tools** across both **Windows** and **Linux** (distribution-agnostic) environments from a single zero-dependency standalone binary. --- -## Features +## Features (`v2.0.0`) - **🩺 Full Machine Health Check & Score (`health:check`):** - Calculates an objective **0–100 Health Score** across RAM usage, disk storage, internet/DNS connectivity, print queue state, and critical OS logs, classifying the workstation into **Healthy (`80–100`)**, **Warning (`50–79`)**, or **Critical (`0–49`)** with visual progress bar, checklist (`✅` / `⚠️` / `❌`), and actionable remediation recommendations. -- **🖥 System & Hardware Diagnostics (`system`):** - - Inspect OS metadata, kernel version, architecture, hostname, and system uptime. - - Real-time CPU model, core/thread count, load percentage, and physical RAM usage. - - Storage volume capacity, used/free space, and usage percentages across NTFS/ext4/btrfs/xfs filesystems. - - Top resource-consuming processes viewer with interactive frozen process termination (`PID` kill). - - **Critical OS Logs & Recent Errors (`system:logs`):** Inspect critical and error events recorded in the last 24 hours (`Get-WinEvent` on Windows / `journalctl -p err` & `/var/log/syslog` on Linux). +- **🖥 System, Hardware & Services (`system`):** + - `system:info`: OS metadata, kernel/build, CPU model/load, physical RAM, and disk usage alerts (`> 85%`). + - `system:top` & `system:kill`: Top resource-consuming processes viewer and force-termination by PID, name, or interactive selection. + - `system:logs`: Critical & error OS event logs from the last 24h (`Get-WinEvent` / `journalctl -p err` / `/var/log/syslog`). + - `system:services`: Status and one-click restart for critical support services (`Spooler`, `wuauserv`, `BITS`, `Dnscache`, `AnyDesk`, `TeamViewer`, `cups`, `ssh`, `docker`, `nginx`, `NetworkManager`). + - `system:battery`: Laptop battery charge, design vs full capacity (mWh), wear percentage, and cycle count. + - `system:startup`: Boot & login startup programs (`Win32_StartupCommand` / `systemctl list-unit-files --state=enabled`). + - `system:usb`: Connected USB controllers and peripherals (`Get-PnpDevice` / `lsusb`). + - `system:env`: Environment variable inspector and `PATH` directory auditor (`✅ Valid`, `❌ Missing/Broken`, `⚠️ Duplicate`). - **🖨 Printers & Spooler Management (`printer`):** - - List installed printers, driver details, ports/URIs, default status, and queue states (`PowerShell Get-Printer` on Windows / `CUPS lpstat` on Linux). - - One-step print queue purge and spooler service restart (`net stop/start spooler` & `PRINTERS` cleanup on Windows / `cancel -a` & `systemctl restart cups` on Linux). -- **🌐 Network & Connectivity Diagnostics (`network`):** - - Active network interface inspection (`IPv4`, `IPv6`, `MAC`, link status). - - Automated connectivity health check (Default Gateway ping, external ICMP latency to `8.8.8.8` / `1.1.1.1`, and DNS resolution verification). - - One-click DNS cache flush and DHCP IP lease renewal. - - Active listening `TCP`/`UDP` ports and owning processes scanner (`Get-NetTCPConnection` / `ss -tulnp`). + - `printer:list` & `printer:clear`: List installed printers, drivers, ports/URIs, pending jobs, and restart Print Spooler / CUPS purging stuck queues. + - `printer:test-page` & `printer:default`: Send a diagnostic test page (`Win32_Printer.PrintTestPage` / `lp -d`) and switch the system default printer (`SetDefaultPrinter` / `lpoptions -d`). +- **🌐 Advanced Network & Connectivity (`network`):** + - `network:check`, `network:flush` & `network:ports`: Interfaces (IPv4/IPv6/Gateway/DNS/MAC), cascade connectivity test, DNS flush, and active listening ports (`Get-NetTCPConnection` / `ss -tulnp`). + - `network:probe`: Native TCP port connection probe with millisecond latency measurement (`OPEN` / `CLOSED` / `TIMEOUT`). + - `network:wifi`: Wireless signal strength (`%`), SSID, BSSID, channel, band, and RX/TX link speeds (`netsh wlan` / `nmcli` / `iw`). + - `network:reset`: Full network stack & DHCP reset (`ipconfig /release`, `netsh winsock reset`, `netsh int ip reset`, `ipconfig /renew` / `NetworkManager` & `dhclient`). + - `network:ssl`: Live HTTPS SSL/TLS certificate inspector (CN, Issuer, expiration date, `< 30` days warning, SANs). + - `network:scan`: Local Area Network (LAN) active devices discovery via ARP & neighbor cache. + - `network:public`: External Public IP, City/Region/Country, ISP/ASN, and reverse hostname lookup. - **🧹 System Maintenance & Cleanup (`maintenance`):** - - Safe cleanup of user and system temporary directories (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`, `~/.cache/thumbnails`), gracefully skipping locked/in-use files and reporting freed disk space. -- **📄 Diagnostic Reports & Export (`report`):** - - Export complete hardware, OS, printer, and network diagnostic snapshots to structured `.md` and `.json` files for ticketing systems and audit logs. -- **⬆️ Over-the-Air Self-Update (`self:update`):** - - Automatically queries GitHub Releases for newer versions and atomically updates the running standalone binary (`.exe`, Linux ELF, or `.phar`) in-place. -- **🌍 Native Bilingual Interface (`i18n`):** - - Full support for **English (`en`)** and **Brazilian Portuguese (`pt_BR`)**, selectable via `--lang=` flag or dynamically inside the interactive numeric TUI menu. + - `clean:temp`: Safe cleanup of user/system temp directories (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`) + DNS flush / `journalctl --vacuum-time=3d`. + - `maintenance:browsers`: Cleans **only** cache directories for Chrome, Edge, and Firefox (preserving passwords, history, cookies, and bookmarks). + - `maintenance:large-files`: Recursive scanner locating the largest disk-consuming files cleanly. + - `maintenance:repair`: OS image & package integrity verification (`sfc /scannow` + `DISM` / `dpkg --audit` / `apt-get check` / `rpm -Va` / `pacman -Qk`). + - `maintenance:updates` & `maintenance:scheduler`: Pending OS/package updates (`Microsoft.Update.Session` / `apt` / `dnf` / `pacman`) and active non-system scheduled tasks, cron jobs & systemd timers. +- **🛡 Security & Access Auditing (`security`):** + - `security:audit`: Unified posture check for Firewall (`Windows Defender Firewall` / `ufw` / `firewalld` / `nftables`), Antivirus/MAC (`Microsoft Defender` / `AppArmor` / `SELinux`), and Elevation Policy (`UAC` / `SSH PermitRootLogin`). + - `security:users`: Local accounts audit highlighting `Administrators` / `sudo` / `wheel` / `root` members. + - `security:shares`: Active SMB, Samba, and NFS network shares inspector. + - `security:hosts`: System `hosts` file parser alerting on custom overrides and external domain redirections. +- **📄 Reports, Asset Inventory & Benchmark (`report` / `toolbox`):** + - `report:export`: Export full diagnostic snapshots to structured `.md` and `.json` files. + - `toolbox:inventory`: Corporate IT asset technical sheet (Hostname, Manufacturer, Model, BIOS Serial Number, RAM modules, Physical SSD/HDD/NVMe drives, MAC addresses) ready for GLPI / CMDB export. + - `toolbox:benchmark`: Zero-dependency CPU single-core (`SHA-256` ops/sec) and 64 MB sequential Disk I/O (`MB/s` write/read) micro-benchmark. +- **⬆️ Over-the-Air Self-Update (`self:update`) & Bilingual Numeric TUI (`en` / `pt_BR`):** + - Fast numeric keyboard navigation (`[1]`–`[9]`, `[0]`) with automatic terminal screen clearing, privilege badge (`Admin / Root` vs `Standard User`), and atomic GitHub Releases self-updating. --- ## Architecture -The project strictly separates presentation (TUI commands), orchestration, and operating-system-specific execution using the **Adapter/Driver Pattern** and **Factory Pattern**. All external OS commands are executed safely through `Symfony\Component\Process\Process` using argument arrays to prevent Command Injection. +The project strictly separates presentation (numeric TUI commands), domain services, and operating-system-specific execution using the **Adapter/Driver Pattern**, **Factory Pattern**, and **Process Executor Abstraction**. All external OS commands execute safely via `Symfony\Component\Process\Process` using argument arrays to prevent Command Injection. ```mermaid flowchart TD User(["IT Technician / SysAdmin"]) --> CLI["CLI Entrypoint (it-toolbox)"] - CLI --> Menu["ToolboxMenuCommand / Subcommands (Laravel Prompts)"] + CLI --> Menu["ToolboxMenuCommand (Numeric TUI + Screen Clear)"] Menu --> I18n["Translator Service (lang/en & lang/pt_BR)"] + Menu --> Services["Services: HealthCheck, ReportExporter, SelfUpdate"] Menu --> Factory["SystemDriverFactory::make(PHP_OS_FAMILY)"] + Services --> Factory Factory -->|Windows| WinDriver["WindowsDriver (SystemDriverInterface)"] Factory -->|Linux| LinDriver["LinuxDriver (SystemDriverInterface)"] - WinDriver --> WinProcess["Symfony Process (Argument Arrays)"] - LinDriver --> LinProcess["Symfony Process / Native Filesystem"] + WinDriver --> Executor["ProcessExecutorInterface / Native Sockets & FS"] + LinDriver --> Executor - WinProcess --> WinAPI["PowerShell CIM / WMI / net / ipconfig / taskkill"] - LinProcess --> LinAPI["/proc / POSIX / CUPS (lpstat/cancel) / ip / ss / resolvectl"] + Executor --> WinAPI["PowerShell CIM/WMI, netsh, Get-WinEvent, SFC/DISM, SMB"] + Executor --> LinAPI["/proc, /sys, POSIX, CUPS, ip/ss/nmcli, journalctl, UFW"] WinAPI --> DTO["ActionResult Readonly DTO"] LinAPI --> DTO @@ -81,7 +98,10 @@ Ideal for field IT technicians and target workstations. Download the self-contai **Windows (x64):** ```powershell -# Download 'it-toolbox-windows-x64.exe' from GitHub Releases and run: +# If Windows SmartScreen blocks the downloaded executable from the internet, unblock it first: +Unblock-File -Path .\it-toolbox-windows-x64.exe + +# Run the interactive TUI: .\it-toolbox-windows-x64.exe # Or launch directly in your preferred language: @@ -89,6 +109,8 @@ Ideal for field IT technicians and target workstations. Download the self-contai .\it-toolbox-windows-x64.exe --lang=pt_BR ``` +> **Windows SmartScreen Note:** Because `it-toolbox-windows-x64.exe` is an unsigned open-source binary downloaded from GitHub, Windows Defender SmartScreen may display a prompt on first launch. You can either run `Unblock-File -Path .\it-toolbox-windows-x64.exe` in PowerShell or click **More info → Run anyway**. + **Linux (x64):** ```bash # Download 'it-toolbox-linux-x64' from GitHub Releases, grant execution permission, and run: @@ -121,20 +143,15 @@ cd it-toolbox-cli composer install ``` -> **Note:** Administrator privileges (Windows) or `sudo` (Linux) are recommended for privileged system operations (spooler restart, system temp cleanup, and DHCP renewal). +> **Note:** Administrator privileges (Windows) or `sudo` (Linux) are recommended for privileged system operations (spooler restart, OS repair, network stack reset, service restarts, and system temp cleanup). ### Interactive TUI Mode -Launch the interactive dashboard. If `--lang` is omitted, an interactive language selector is presented on startup: +Launch the interactive numeric dashboard. If `--lang` is omitted, an interactive language selector is presented on startup: ```bash -# Launch with interactive language selector php it-toolbox - -# Launch directly in English php it-toolbox --lang=en - -# Launch directly in Brazilian Portuguese php it-toolbox --lang=pt_BR ``` @@ -144,19 +161,44 @@ Every module can also be executed directly in headless/CLI scripts or terminal s | Command | Module | Description | Options | | :--- | :--- | :--- | :--- | -| `php it-toolbox menu` | Core TUI | Launch the interactive numeric TUI main menu (default command) | `--lang=en\|pt_BR`, `--once` | -| `php it-toolbox health:check` | Health | Run a full machine health audit with a 0–100 score and recommendations | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox menu` | Core TUI | Launch the interactive numeric TUI main menu (default) | `--lang=en\|pt_BR`, `--once` | +| `php it-toolbox health:check` | Health | Run full machine health audit with 0–100 score & tips | `--export`, `--lang=en\|pt_BR` | | `php it-toolbox system:info` | System | Display OS, CPU, RAM, and disk health metrics | `--lang=en\|pt_BR` | -| `php it-toolbox system:top` | System | List top processes by resource usage and optionally kill a PID | `--limit=10`, `--lang=en\|pt_BR` | -| `php it-toolbox system:logs` | System | Inspect critical and error OS log events from the last 24 hours | `--limit=15`, `--lang=en\|pt_BR` | -| `php it-toolbox printer:list` | Printers | List installed printers, drivers, ports, and status | `--lang=en\|pt_BR` | -| `php it-toolbox printer:clear` | Printers | Restart print spooler / CUPS and purge stuck print jobs | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:check` | Network | Inspect network interfaces and run ping/DNS health checks | `--lang=en\|pt_BR` | +| `php it-toolbox system:top` | System | List top processes by resource usage and kill a PID | `--limit=10`, `--lang=en\|pt_BR` | +| `php it-toolbox system:logs` | System | Inspect critical/error OS log events (last 24h) | `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox system:services` | System | Inspect critical IT support services & restart one | `--restart=NAME`, `--lang=en\|pt_BR` | +| `php it-toolbox system:battery` | System | Inspect laptop battery health, capacity & wear | `--lang=en\|pt_BR` | +| `php it-toolbox system:startup` | System | List boot & login startup programs / services | `--lang=en\|pt_BR` | +| `php it-toolbox system:usb` | System | List connected USB controllers & peripherals | `--lang=en\|pt_BR` | +| `php it-toolbox system:env` | System | Inspect env variables & audit PATH entries | `--lang=en\|pt_BR` | +| `php it-toolbox system:kill` | System | Force-kill process by PID, name, or top-10 menu | `[target]`, `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:list` | Printers | List installed printers, drivers, ports, and jobs | `--lang=en\|pt_BR` | +| `php it-toolbox printer:clear` | Printers | Restart print spooler / CUPS and purge print queue | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:test-page` | Printers | Send a diagnostic test page to an installed printer | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:default` | Printers | Set the system default printer | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox network:check` | Network | Inspect network interfaces & run ping/DNS check | `--lang=en\|pt_BR` | | `php it-toolbox network:flush` | Network | Flush DNS resolver cache and renew DHCP lease | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:ports` | Network | List active listening TCP/UDP ports and owning processes | `--lang=en\|pt_BR` | +| `php it-toolbox network:ports` | Network | List active listening TCP/UDP ports & processes | `--lang=en\|pt_BR` | +| `php it-toolbox network:probe` | Network | Test remote TCP port connectivity & latency (ms) | `[host] [port]`, `--timeout=3`, `--lang=...` | +| `php it-toolbox network:wifi` | Network | Inspect Wi-Fi SSID, BSSID, signal %, channel & speed | `--lang=en\|pt_BR` | +| `php it-toolbox network:reset` | Network | Full network stack reset (Winsock/IP/NetworkManager) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox network:ssl` | Network | Inspect HTTPS SSL/TLS certificate & days remaining | `[domain]`, `--port=443`, `--lang=en\|pt_BR` | +| `php it-toolbox network:scan` | Network | Discover active LAN devices from ARP / neighbor table | `--lang=en\|pt_BR` | +| `php it-toolbox network:public` | Network | Query external public IP, geolocation, ISP & PTR | `--lang=en\|pt_BR` | | `php it-toolbox clean:temp` | Maintenance | Safely purge temporary files and report freed space | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox report:export` | Reports | Export full system diagnostic report to `.md` and/or `.json` | `--format=md\|json\|both`, `--output=DIR`, `--lang=en\|pt_BR` | -| `php it-toolbox self:update` | Core CLI | Check GitHub Releases and self-update the running executable | `--check`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:browsers` | Maintenance | Clean Chrome, Edge & Firefox cache directories only | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:large-files` | Maintenance | Find the top largest files consuming disk space | `[path]`, `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:repair` | Maintenance | Verify/repair OS files & packages (SFC/DISM/dpkg) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:updates` | Maintenance | Check pending OS patches & package updates | `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:scheduler` | Maintenance | List active scheduled tasks, cron jobs & timers | `--lang=en\|pt_BR` | +| `php it-toolbox security:audit` | Security | Audit Firewall, Antivirus/MAC & UAC/SSH policy | `--lang=en\|pt_BR` | +| `php it-toolbox security:users` | Security | Audit local user accounts & Admin/sudo membership | `--lang=en\|pt_BR` | +| `php it-toolbox security:shares` | Security | List active SMB, Samba, and NFS network shares | `--lang=en\|pt_BR` | +| `php it-toolbox security:hosts` | Security | Audit system hosts file for custom/external redirects | `--lang=en\|pt_BR` | +| `php it-toolbox report:export` | Reports | Export full system diagnostic report (`.md` / `.json`) | `--format=md\|json\|both`, `--output=DIR`, `--lang=...` | +| `php it-toolbox toolbox:inventory` | Asset | Generate GLPI/CMDB hardware & BIOS serial inventory | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox toolbox:benchmark` | Diagnostic | Run CPU SHA-256 & 64 MB sequential Disk I/O bench | `--lang=en\|pt_BR` | +| `php it-toolbox self:update` | Core CLI | Check GitHub Releases and self-update executable | `--check`, `--lang=en\|pt_BR` | --- @@ -168,15 +210,15 @@ Compile the application into a portable `.phar` (`builds/it-toolbox`) or bundle ```bash # Build portable PHAR only -php it-toolbox app:build it-toolbox --build-version=1.0.0 +php -d phar.readonly=0 it-toolbox app:build it-toolbox --build-version=2.0.0 # Build PHAR + Native Linux & Windows x64 standalone binaries -./scripts/build-standalone.sh 1.0.0 +./scripts/build-standalone.sh 2.0.0 ``` ### Running the Test Suite -The test suite is powered by **Pest PHP** and mocks OS-level processes so all tests run deterministically on both Windows and Linux CI runners: +The test suite is powered by **Pest PHP** and mocks OS-level processes via `ProcessExecutorInterface` so all tests run deterministically on both Windows and Linux CI runners: ```bash # Run all Unit and Feature tests @@ -192,13 +234,13 @@ The test suite is powered by **Pest PHP** and mocks OS-level processes so all te - **Language & Runtime:** PHP 8.3+ (`declare(strict_types=1)`, typed properties, `match` expressions, `readonly` classes) - **Micro-Framework:** [Laravel Zero](https://laravel-zero.com/) -- **Terminal UI (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) (`select`, `table`, `spin`, `confirm`, `info`, `warning`, `error`) -- **Process Execution:** `Symfony\Component\Process\Process` (strictly array-based arguments for Command Injection prevention) -- **Internationalization:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR`) +- **Terminal UI (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) + Custom Cross-Platform Numeric TTY Navigation (`InteractsWithTerminal`) +- **Process Execution:** `Symfony\Component\Process\Process` abstracted behind `ProcessExecutorInterface` (strictly array-based arguments for Command Injection prevention) +- **Internationalization:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR` with 100% key parity enforced by CI tests) - **Architectural Patterns:** - **Adapter / Driver Pattern:** `SystemDriverInterface` implemented by `WindowsDriver` and `LinuxDriver`. - **Factory Pattern:** `SystemDriverFactory` dynamically resolves the driver via `PHP_OS_FAMILY`. - - **Data Transfer Objects (DTO):** Immutable `readonly class ActionResult` for standardized operation outcomes. + - **Data Transfer Objects (DTO):** Immutable `readonly class ActionResult` and `ProcessResult`. - **Testing & QA:** Pest PHP, Mockery, Laravel Pint, and GitHub Actions CI across Ubuntu and Windows runners. --- diff --git a/README.pt-BR.md b/README.pt-BR.md index bd51cfc..4f43b86 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -11,58 +11,75 @@ ## Visão Geral -O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TUI/CLI) multiplataforma desenvolvido em **PHP 8.3+**, **Laravel Zero** e **Laravel Prompts**. Projetado para **Técnicos de Suporte de TI, Analistas de Help Desk e Administradores de Sistemas (SysAdmins)**, ele centraliza tarefas diárias de diagnóstico de hardware e SO, recuperação de filas de impressão (spooler/CUPS), testes de saúde de rede e limpeza segura de arquivos temporários em ambientes **Windows** e **Linux** (agnóstico de distribuição) a partir de um único binário portátil. +O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TUI/CLI) multiplataforma desenvolvido em **PHP 8.3+**, **Laravel Zero** e **Laravel Prompts**. Projetado para **Técnicos de Suporte de TI, Analistas de Help Desk e Administradores de Sistemas (SysAdmins)**, ele centraliza **mais de 35 ferramentas de diagnóstico, manutenção, segurança, impressoras, rede e inventário patrimonial** em ambientes **Windows** e **Linux** (agnóstico de distribuição) a partir de um único binário autossuficiente sem dependências. --- -## Funcionalidades +## Funcionalidades (`v2.0.0`) - **🩺 Check-up Geral & Score de Saúde da Máquina (`health:check`):** - Calcula um **Score de Saúde objetivo de 0 a 100 pontos** auditando consumo de RAM, armazenamento em disco, conectividade externa/DNS, fila de impressão e logs críticos do SO, classificando a máquina em **Saudável (`80–100`)**, **Atenção (`50–79`)** ou **Crítico (`0–49`)** com barra visual de integridade, checklist (`✅` / `⚠️` / `❌`) e recomendações práticas de correção. -- **🖥 Diagnóstico de Sistema e Hardware (`system`):** - - Inspeção de metadados do SO, versão do kernel, arquitetura, hostname e tempo de atividade (`uptime`). - - Modelo da CPU, contagem de núcleos/threads, percentual de carga em tempo real e uso de memória RAM física. - - Capacidade de volumes de armazenamento, espaço usado/livre e percentual de ocupação em sistemas de arquivos NTFS/ext4/btrfs/xfs. - - Visualizador dos processos de maior consumo com opção interativa para encerrar tarefas travadas (`kill PID`). - - **Logs Críticos do SO & Erros Recentes (`system:logs`):** Inspeção de eventos críticos e erros registrados nas últimas 24 horas (`Get-WinEvent` no Windows / `journalctl -p err` e `/var/log/syslog` no Linux). +- **🖥 Sistema, Hardware & Serviços (`system`):** + - `system:info`: Metadados do SO, kernel/build, modelo/carga de CPU, RAM física e alerta de discos (`> 85%`). + - `system:top` & `system:kill`: Visualizador dos processos que mais consomem recursos e encerramento forçado por PID, nome ou seleção numérica. + - `system:logs`: Eventos críticos e erros do SO nas últimas 24h (`Get-WinEvent` / `journalctl -p err` / `/var/log/syslog`). + - `system:services`: Status e reinicialização rápida de serviços críticos de suporte (`Spooler`, `wuauserv`, `BITS`, `Dnscache`, `AnyDesk`, `TeamViewer`, `cups`, `ssh`, `docker`, `nginx`, `NetworkManager`). + - `system:battery`: Nível de carga, capacidade projetada vs atual (mWh), desgaste e ciclos da bateria. + - `system:startup`: Programas e serviços configurados na inicialização/boot (`Win32_StartupCommand` / `systemctl list-unit-files --state=enabled`). + - `system:usb`: Controladores e periféricos USB conectados (`Get-PnpDevice` / `lsusb`). + - `system:env`: Auditoria de variáveis de ambiente e validação de diretórios do `PATH` (`✅ Válido`, `❌ Inexistente/Quebrado`, `⚠️ Duplicado`). - **🖨 Gerenciamento de Impressoras e Spooler (`printer`):** - - Listagem de impressoras instaladas, detalhes de drivers, portas/URIs, impressora padrão e status da fila (`PowerShell Get-Printer` no Windows / `CUPS lpstat` no Linux). - - Limpeza automatizada de fila de impressão e reinicialização do serviço de spooler (`net stop/start spooler` e limpeza de `PRINTERS` no Windows / `cancel -a` e `systemctl restart cups` no Linux). -- **🌐 Diagnóstico de Rede e Conectividade (`network`):** - - Inspeção de interfaces de rede ativas (`IPv4`, `IPv6`, `MAC`, estado do link). - - Verificação automatizada de saúde de conectividade (Ping para o Gateway Padrão, latência ICMP externa para `8.8.8.8` / `1.1.1.1` e validação de resolução DNS). - - Limpeza de cache DNS e renovação de concessão DHCP com um comando. - - Scanner de portas `TCP`/`UDP` abertas em escuta e processos proprietários (`Get-NetTCPConnection` / `ss -tulnp`). -- **🧹 Manutenção e Limpeza do Sistema (`maintenance`):** - - Limpeza segura de diretórios temporários de usuário e sistema (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`, `~/.cache/thumbnails`), ignorando arquivos em uso/bloqueados com segurança e contabilizando o espaço em disco liberado. -- **📄 Relatórios de Diagnóstico e Exportação (`report`):** - - Exportação de relatórios completos de diagnóstico de hardware, SO, impressoras e rede nos formatos `.md` e `.json` para anexação em chamados técnicos e auditorias. -- **⬆️ Auto-Atualização via GitHub Releases (`self:update`):** - - Consulta automaticamente a API do GitHub Releases em busca de novas versões e atualiza o binário em execução (`.exe`, binário Linux ou `.phar`) de forma atômica. -- **🌍 Interface Bilíngue Nativa (`i18n`):** - - Suporte completo para **Inglês (`en`)** e **Português do Brasil (`pt_BR`)**, selecionável via flag `--lang=` ou dinamicamente dentro do menu interativo numérico TUI. + - `printer:list` & `printer:clear`: Listagem de impressoras, drivers, portas/URIs, jobs pendentes e reinício do Spooler / CUPS com limpeza da fila. + - `printer:test-page` & `printer:default`: Envio de página de teste diagnóstica (`Win32_Printer.PrintTestPage` / `lp -d`) e definição da impressora padrão (`SetDefaultPrinter` / `lpoptions -d`). +- **🌐 Diagnóstico Avançado de Rede & Conectividade (`network`):** + - `network:check`, `network:flush` & `network:ports`: Interfaces (IPv4/IPv6/Gateway/DNS/MAC), teste em cascata, limpeza de DNS e portas em escuta (`Get-NetTCPConnection` / `ss -tulnp`). + - `network:probe`: Teste de porta TCP remota com medição de latência em milissegundos (`OPEN` / `CLOSED` / `TIMEOUT`). + - `network:wifi`: Qualidade do sinal Wi-Fi (`%`), SSID, BSSID, canal, banda e velocidade RX/TX (`netsh wlan` / `nmcli` / `iw`). + - `network:reset`: Reset completo da pilha de rede e DHCP (`ipconfig /release`, `netsh winsock reset`, `netsh int ip reset`, `ipconfig /renew` / `NetworkManager` & `dhclient`). + - `network:ssl`: Inspetor de certificado SSL/TLS HTTPS (CN, Emissor, validade, alerta `< 30` dias e SANs). + - `network:scan`: Descoberta de dispositivos ativos na rede local (LAN) via tabela ARP / vizinhos. + - `network:public`: Consulta de IP público externo, Cidade/Região/País, Provedor (ISP/ASN) e Hostname reverso. +- **🧹 Manutenção Avançada & Limpeza (`maintenance`):** + - `clean:temp`: Limpeza segura de diretórios temporários (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`) + flush DNS / `journalctl --vacuum-time=3d`. + - `maintenance:browsers`: Limpa **exclusivamente** arquivos de cache do Chrome, Edge e Firefox (preservando senhas, histórico, cookies e favoritos). + - `maintenance:large-files`: Varredura recursiva para localizar os maiores arquivos ocupando espaço em disco. + - `maintenance:repair`: Verificação e reparo de integridade de arquivos/pacotes do SO (`sfc /scannow` + `DISM` / `dpkg --audit` / `apt-get check` / `rpm -Va` / `pacman -Qk`). + - `maintenance:updates` & `maintenance:scheduler`: Atualizações pendentes (`Microsoft.Update.Session` / `apt` / `dnf` / `pacman`) e tarefas agendadas, cron jobs & systemd timers ativos. +- **🛡 Segurança & Auditoria de Acesso (`security`):** + - `security:audit`: Painel unificado verificando Firewall (`Windows Defender Firewall` / `ufw` / `firewalld` / `nftables`), Antivírus/MAC (`Microsoft Defender` / `AppArmor` / `SELinux`) e Política de Elevação (`UAC` / `SSH PermitRootLogin`). + - `security:users`: Auditoria de usuários locais destacando membros de `Administrators` / `sudo` / `wheel` / `root`. + - `security:shares`: Inspetor de compartilhamentos de rede SMB, Samba e NFS ativos. + - `security:hosts`: Analisador do arquivo `hosts` com alertas para redirecionamentos customizados ou externos. +- **📄 Relatórios, Inventário Patrimonial & Benchmark (`report` / `toolbox`):** + - `report:export`: Exportação de relatórios completos de diagnóstico em `.md` e `.json`. + - `toolbox:inventory`: Ficha técnica patrimonial (Hostname, Fabricante, Modelo, Serial BIOS, módulos de RAM, discos físicos SSD/HDD/NVMe e MACs) pronta para GLPI / CMDB. + - `toolbox:benchmark`: Micro-benchmark rápido sem dependências de CPU single-core (`SHA-256` ops/s) e velocidade sequencial de disco de 64 MB (`MB/s` escrita/leitura). +- **⬆️ Auto-Atualização (`self:update`) & TUI Numérica Bilíngue (`en` / `pt_BR`):** + - Navegação rápida por teclas numéricas (`[1]`–`[9]`, `[0]`) com limpeza automática de tela, indicador de privilégio (`Admin / Root` vs `Usuário Padrão`) e atualização atômica via GitHub Releases. --- ## Arquitetura -O projeto separa estritamente a camada de apresentação (comandos TUI), orquestração e execução específica de cada sistema operacional utilizando **Adapter/Driver Pattern** e **Factory Pattern**. Todos os comandos externos do SO são executados de forma segura via `Symfony\Component\Process\Process` utilizando arrays de argumentos para prevenir *Command Injection*. +O projeto separa estritamente a camada de apresentação (comandos TUI numéricos), serviços de domínio e execução específica de cada sistema operacional utilizando **Adapter/Driver Pattern**, **Factory Pattern** e **Abstração de Execução de Processos**. Todos os comandos externos do SO são executados de forma segura via `Symfony\Component\Process\Process` utilizando arrays de argumentos para prevenir *Command Injection*. ```mermaid flowchart TD User(["Técnico de TI / SysAdmin"]) --> CLI["Entrypoint CLI (it-toolbox)"] - CLI --> Menu["ToolboxMenuCommand / Subcomandos (Laravel Prompts)"] + CLI --> Menu["ToolboxMenuCommand (TUI Numérica + Limpeza de Tela)"] Menu --> I18n["Serviço Translator (lang/en & lang/pt_BR)"] + Menu --> Services["Serviços: HealthCheck, ReportExporter, SelfUpdate"] Menu --> Factory["SystemDriverFactory::make(PHP_OS_FAMILY)"] + Services --> Factory Factory -->|Windows| WinDriver["WindowsDriver (SystemDriverInterface)"] Factory -->|Linux| LinDriver["LinuxDriver (SystemDriverInterface)"] - WinDriver --> WinProcess["Symfony Process (Arrays de Argumentos)"] - LinDriver --> LinProcess["Symfony Process / Filesystem Nativo"] + WinDriver --> Executor["ProcessExecutorInterface / Sockets & FS Nativos"] + LinDriver --> Executor - WinProcess --> WinAPI["PowerShell CIM / WMI / net / ipconfig / taskkill"] - LinProcess --> LinAPI["/proc / POSIX / CUPS (lpstat/cancel) / ip / ss / resolvectl"] + Executor --> WinAPI["PowerShell CIM/WMI, netsh, Get-WinEvent, SFC/DISM, SMB"] + Executor --> LinAPI["/proc, /sys, POSIX, CUPS, ip/ss/nmcli, journalctl, UFW"] WinAPI --> DTO["ActionResult Readonly DTO"] LinAPI --> DTO @@ -81,7 +98,10 @@ Ideal para técnicos de TI em campo e máquinas de clientes. Baixe o executável **Windows (x64):** ```powershell -# Baixe 'it-toolbox-windows-x64.exe' na aba Releases do GitHub e execute: +# Caso o Windows SmartScreen bloqueie o executável baixado da internet, desbloqueie primeiro: +Unblock-File -Path .\it-toolbox-windows-x64.exe + +# Execute a TUI interativa: .\it-toolbox-windows-x64.exe # Ou inicie diretamente no idioma desejado: @@ -89,6 +109,8 @@ Ideal para técnicos de TI em campo e máquinas de clientes. Baixe o executável .\it-toolbox-windows-x64.exe --lang=en ``` +> **Nota sobre o Windows SmartScreen:** Como o `it-toolbox-windows-x64.exe` é um binário open-source sem assinatura digital comercial baixado do GitHub, o Windows Defender SmartScreen pode exibir um aviso na primeira execução. Basta rodar `Unblock-File -Path .\it-toolbox-windows-x64.exe` no PowerShell ou clicar em **Mais informações → Executar assim mesmo**. + **Linux (x64):** ```bash # Baixe 'it-toolbox-linux-x64' na aba Releases, conceda permissão de execução e rode: @@ -121,20 +143,15 @@ cd it-toolbox-cli composer install ``` -> **Nota:** Privilégios de Administrador (Windows) ou `sudo` (Linux) são recomendados para operações privilegiadas do sistema (reinício do spooler, limpeza temporária do sistema e renovação DHCP). +> **Nota:** Privilégios de Administrador (Windows) ou `sudo` (Linux) são recomendados para operações privilegiadas do sistema (reinício do spooler, reparo do SO, reset da pilha de rede, reinício de serviços e limpeza temporária do sistema). ### Modo Interativo (TUI) -Inicie o painel interativo. Caso a flag `--lang` seja omitida, o seletor interativo de idioma será exibido na inicialização: +Inicie o painel interativo numérico. Caso a flag `--lang` seja omitida, o seletor interativo de idioma será exibido na inicialização: ```bash -# Iniciar com seletor interativo de idioma php it-toolbox - -# Iniciar diretamente em Português (Brasil) php it-toolbox --lang=pt_BR - -# Iniciar diretamente em Inglês php it-toolbox --lang=en ``` @@ -144,19 +161,44 @@ Cada módulo também pode ser executado diretamente em scripts ou sessões rápi | Comando | Módulo | Descrição | Opções | | :--- | :--- | :--- | :--- | -| `php it-toolbox menu` | Core TUI | Inicia o menu principal interativo numérico TUI (comando padrão) | `--lang=en\|pt_BR`, `--once` | -| `php it-toolbox health:check` | Saúde | Executa auditoria completa com Score de Saúde (0–100) e recomendações | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox menu` | Core TUI | Inicia o menu principal interativo numérico TUI (padrão) | `--lang=en\|pt_BR`, `--once` | +| `php it-toolbox health:check` | Saúde | Executa auditoria completa com Score (0–100) e dicas | `--export`, `--lang=en\|pt_BR` | | `php it-toolbox system:info` | Sistema | Exibe métricas de SO, CPU, RAM e saúde de discos | `--lang=en\|pt_BR` | -| `php it-toolbox system:top` | Sistema | Lista os processos de maior consumo e permite encerrar um PID | `--limit=10`, `--lang=en\|pt_BR` | -| `php it-toolbox system:logs` | Sistema | Exibe eventos críticos e erros de log do SO nas últimas 24 horas | `--limit=15`, `--lang=en\|pt_BR` | -| `php it-toolbox printer:list` | Impressoras | Lista impressoras instaladas, drivers, portas e status | `--lang=en\|pt_BR` | -| `php it-toolbox printer:clear` | Impressoras | Reinicia o Spooler / CUPS e limpa trabalhos de impressão travados | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:check` | Rede | Inspeciona interfaces de rede e executa testes de ping e DNS | `--lang=en\|pt_BR` | -| `php it-toolbox network:flush` | Rede | Limpa o cache DNS e renova a concessão de IP via DHCP | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:ports` | Rede | Lista portas TCP/UDP em escuta e seus respectivos processos | `--lang=en\|pt_BR` | -| `php it-toolbox clean:temp` | Manutenção | Limpa diretórios temporários com segurança e exibe espaço liberado | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox report:export` | Relatórios | Exporta relatório completo de diagnóstico em `.md` e/ou `.json` | `--format=md\|json\|both`, `--output=DIR`, `--lang=en\|pt_BR` | -| `php it-toolbox self:update` | Core CLI | Verifica novas versões no GitHub Releases e auto-atualiza o binário | `--check`, `--lang=en\|pt_BR` | +| `php it-toolbox system:top` | Sistema | Lista processos de maior consumo e encerra por PID | `--limit=10`, `--lang=en\|pt_BR` | +| `php it-toolbox system:logs` | Sistema | Exibe eventos críticos e erros do SO (últimas 24h) | `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox system:services` | Sistema | Inspeciona e reinicia serviços críticos de suporte | `--restart=NOME`, `--lang=en\|pt_BR` | +| `php it-toolbox system:battery` | Sistema | Saúde da bateria, capacidade projetada e ciclos | `--lang=en\|pt_BR` | +| `php it-toolbox system:startup` | Sistema | Lista programas e serviços de inicialização/boot | `--lang=en\|pt_BR` | +| `php it-toolbox system:usb` | Sistema | Lista controladores e periféricos USB conectados | `--lang=en\|pt_BR` | +| `php it-toolbox system:env` | Sistema | Audita variáveis de ambiente e entradas do `PATH` | `--lang=en\|pt_BR` | +| `php it-toolbox system:kill` | Sistema | Encerra processo por PID, nome ou lista top-10 | `[target]`, `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:list` | Impressoras | Lista impressoras instaladas, drivers, portas e jobs | `--lang=en\|pt_BR` | +| `php it-toolbox printer:clear` | Impressoras | Reinicia o Spooler / CUPS e limpa a fila de impressão | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:test-page` | Impressoras | Envia página de teste diagnóstica para impressora | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:default` | Impressoras | Define a impressora padrão do sistema | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox network:check` | Rede | Inspeciona interfaces de rede e testa ping e DNS | `--lang=en\|pt_BR` | +| `php it-toolbox network:flush` | Rede | Limpa o cache DNS e renova a concessão DHCP | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox network:ports` | Rede | Lista portas TCP/UDP em escuta e processos | `--lang=en\|pt_BR` | +| `php it-toolbox network:probe` | Rede | Testa conexão TCP remota e mede latência (ms) | `[host] [port]`, `--timeout=3`, `--lang=...` | +| `php it-toolbox network:wifi` | Rede | Inspeciona SSID, BSSID, sinal %, canal e velocidade | `--lang=en\|pt_BR` | +| `php it-toolbox network:reset` | Rede | Reset completo da pilha de rede (Winsock/IP/DHCP) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox network:ssl` | Rede | Inspeciona certificado SSL/TLS HTTPS e dias restantes | `[domain]`, `--port=443`, `--lang=en\|pt_BR` | +| `php it-toolbox network:scan` | Rede | Descobre dispositivos ativos na LAN via tabela ARP | `--lang=en\|pt_BR` | +| `php it-toolbox network:public` | Rede | Consulta IP público externo, geolocalização e ISP | `--lang=en\|pt_BR` | +| `php it-toolbox clean:temp` | Manutenção | Limpa diretórios temporários e exibe espaço liberado | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:browsers` | Manutenção | Limpa somente cache do Chrome, Edge e Firefox | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:large-files` | Manutenção | Localiza os maiores arquivos ocupando espaço | `[path]`, `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:repair` | Manutenção | Verifica/repara integridade do SO (SFC/DISM/dpkg) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:updates` | Manutenção | Lista atualizações pendentes do SO e pacotes | `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:scheduler` | Manutenção | Lista tarefas agendadas, cron jobs e timers ativos | `--lang=en\|pt_BR` | +| `php it-toolbox security:audit` | Segurança | Audita Firewall, Antivírus/MAC e UAC/SSH | `--lang=en\|pt_BR` | +| `php it-toolbox security:users` | Segurança | Audita contas locais e privilégios Admin/sudo | `--lang=en\|pt_BR` | +| `php it-toolbox security:shares` | Segurança | Lista compartilhamentos de rede SMB, Samba e NFS | `--lang=en\|pt_BR` | +| `php it-toolbox security:hosts` | Segurança | Audita arquivo hosts por redirecionamentos | `--lang=en\|pt_BR` | +| `php it-toolbox report:export` | Relatórios | Exporta relatório completo de diagnóstico (`.md` / `.json`) | `--format=md\|json\|both`, `--output=DIR`, `--lang=...` | +| `php it-toolbox toolbox:inventory` | Inventário | Gera ficha técnica patrimonial de hardware (GLPI/CMDB) | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox toolbox:benchmark` | Diagnóstico | Executa benchmark CPU SHA-256 e I/O disco (64 MB) | `--lang=en\|pt_BR` | +| `php it-toolbox self:update` | Core CLI | Verifica GitHub Releases e auto-atualiza o binário | `--check`, `--lang=en\|pt_BR` | --- @@ -168,15 +210,15 @@ Compile a aplicação em um arquivo `.phar` portátil (`builds/it-toolbox`) ou e ```bash # Compilar apenas o PHAR portátil -php it-toolbox app:build it-toolbox --build-version=1.0.0 +php -d phar.readonly=0 it-toolbox app:build it-toolbox --build-version=2.0.0 # Compilar PHAR + Binários Nativos Standalone (Linux & Windows x64) -./scripts/build-standalone.sh 1.0.0 +./scripts/build-standalone.sh 2.0.0 ``` ### Executando a Suíte de Testes -A suíte de testes utiliza **Pest PHP** com mocks dos processos do sistema operacional para que todos os testes rodem de forma determinística tanto no Windows quanto no Linux (CI): +A suíte de testes utiliza **Pest PHP** com mocks dos processos do sistema operacional via `ProcessExecutorInterface` para que todos os testes rodem de forma determinística tanto no Windows quanto no Linux (CI): ```bash # Executar todos os testes Unitários e de Feature @@ -192,13 +234,13 @@ A suíte de testes utiliza **Pest PHP** com mocks dos processos do sistema opera - **Linguagem & Runtime:** PHP 8.3+ (`declare(strict_types=1)`, propriedades tipadas, expressões `match`, classes `readonly`) - **Micro-Framework:** [Laravel Zero](https://laravel-zero.com/) -- **Interface de Terminal (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) (`select`, `table`, `spin`, `confirm`, `info`, `warning`, `error`) -- **Execução de Processos:** `Symfony\Component\Process\Process` (uso estrito de arrays de argumentos para prevenção de *Command Injection*) -- **Internacionalização:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR`) +- **Interface de Terminal (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) + Navegação Numérica TTY Multiplataforma (`InteractsWithTerminal`) +- **Execução de Processos:** `Symfony\Component\Process\Process` abstraído via `ProcessExecutorInterface` (uso estrito de arrays de argumentos para prevenção de *Command Injection*) +- **Internacionalização:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR` com 100% de paridade validada por testes no CI) - **Padrões de Projeto (Design Patterns):** - **Adapter / Driver Pattern:** `SystemDriverInterface` implementada por `WindowsDriver` e `LinuxDriver`. - **Factory Pattern:** `SystemDriverFactory` resolve dinamicamente o driver ativo via `PHP_OS_FAMILY`. - - **Data Transfer Objects (DTO):** `readonly class ActionResult` imutável para retorno padronizado de operações. + - **Data Transfer Objects (DTO):** `readonly class ActionResult` e `ProcessResult` imutáveis. - **Testes & Qualidade:** Pest PHP, Mockery, Laravel Pint e GitHub Actions CI em runners Ubuntu e Windows. --- diff --git a/app/Commands/Printer/PrintTestPageCommand.php b/app/Commands/Printer/PrintTestPageCommand.php new file mode 100644 index 0000000..4e7891f --- /dev/null +++ b/app/Commands/Printer/PrintTestPageCommand.php @@ -0,0 +1,94 @@ +resolveLocale(); + + info((string) __('messages.printer.test_page_section')); + + $printerArg = $this->argument('printer'); + if (is_string($printerArg) && trim($printerArg) !== '') { + $selectedPrinter = trim($printerArg); + } else { + /** @var array $printers */ + $printers = spin( + callback: fn (): array => $driver->listPrinters(), + message: (string) __('messages.spinners.printer_list'), + ); + + if ($printers === []) { + warning((string) __('messages.printer.no_printers')); + + return self::SUCCESS; + } + + $menuOptions = []; + $indexedPrinters = []; + foreach (array_values($printers) as $idx => $p) { + $num = (string) ($idx + 1); + $indexedPrinters[$num] = $p['name']; + $defaultBadge = strtolower($p['default'] ?? '') === 'yes' ? ' [*]' : ''; + $menuOptions[$num] = sprintf('%s%s (%s)', $p['name'], $defaultBadge, $p['status'] ?? 'Ready'); + } + $menuOptions['0'] = (string) __('messages.common.cancelled'); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.printer.select_printer_prompt'), + options: $menuOptions, + defaultKey: '1', + ); + + if ($choice === '0' || ! isset($indexedPrinters[$choice])) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $selectedPrinter = $indexedPrinters[$choice]; + } + + $result = spin( + callback: fn () => $driver->printTestPage($selectedPrinter), + message: (string) __('messages.spinners.printer_test_page', ['printer' => $selectedPrinter]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Printer/SetDefaultPrinterCommand.php b/app/Commands/Printer/SetDefaultPrinterCommand.php new file mode 100644 index 0000000..bd08f33 --- /dev/null +++ b/app/Commands/Printer/SetDefaultPrinterCommand.php @@ -0,0 +1,94 @@ +resolveLocale(); + + info((string) __('messages.printer.default_section')); + + $printerArg = $this->argument('printer'); + if (is_string($printerArg) && trim($printerArg) !== '') { + $selectedPrinter = trim($printerArg); + } else { + /** @var array $printers */ + $printers = spin( + callback: fn (): array => $driver->listPrinters(), + message: (string) __('messages.spinners.printer_list'), + ); + + if ($printers === []) { + warning((string) __('messages.printer.no_printers')); + + return self::SUCCESS; + } + + $menuOptions = []; + $indexedPrinters = []; + foreach (array_values($printers) as $idx => $p) { + $num = (string) ($idx + 1); + $indexedPrinters[$num] = $p['name']; + $defaultBadge = strtolower($p['default'] ?? '') === 'yes' ? ' (*) [Current Default]' : ''; + $menuOptions[$num] = sprintf('%s%s', $p['name'], $defaultBadge); + } + $menuOptions['0'] = (string) __('messages.common.cancelled'); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.printer.select_default_prompt'), + options: $menuOptions, + defaultKey: '1', + ); + + if ($choice === '0' || ! isset($indexedPrinters[$choice])) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $selectedPrinter = $indexedPrinters[$choice]; + } + + $result = spin( + callback: fn () => $driver->setDefaultPrinter($selectedPrinter), + message: (string) __('messages.spinners.printer_default', ['printer' => $selectedPrinter]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/System/BenchmarkCommand.php b/app/Commands/System/BenchmarkCommand.php new file mode 100644 index 0000000..f29a5e9 --- /dev/null +++ b/app/Commands/System/BenchmarkCommand.php @@ -0,0 +1,48 @@ +resolveLocale(); + + info((string) __('messages.toolbox.benchmark_section')); + + $result = spin( + callback: fn () => $driver->runSystemBenchmark(64, 1.0), + message: (string) __('messages.spinners.toolbox_benchmark'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/System/InventoryCommand.php b/app/Commands/System/InventoryCommand.php new file mode 100644 index 0000000..7163163 --- /dev/null +++ b/app/Commands/System/InventoryCommand.php @@ -0,0 +1,203 @@ +resolveLocale(); + + info((string) __('messages.toolbox.inventory_section')); + + $inventory = spin( + callback: fn (): array => $driver->getHardwareInventory(), + message: (string) __('messages.spinners.toolbox_inventory'), + ); + + info((string) __('messages.toolbox.identity_subsection')); + table( + headers: [ + (string) __('messages.common.metric'), + (string) __('messages.common.value'), + ], + rows: $this->formatMapRows($inventory['system_identity']), + ); + + info((string) __('messages.toolbox.cpu_ram_subsection')); + table( + headers: [ + (string) __('messages.common.metric'), + (string) __('messages.common.value'), + ], + rows: $this->formatMapRows($inventory['processor_memory']), + ); + + info((string) __('messages.toolbox.disks_subsection')); + table( + headers: [ + (string) __('messages.toolbox.disk_headers.model'), + (string) __('messages.toolbox.disk_headers.size'), + (string) __('messages.toolbox.disk_headers.media_type'), + (string) __('messages.toolbox.disk_headers.bus_type'), + ], + rows: array_map( + fn (array $disk): array => [ + $disk['model'] ?? '-', + $disk['size'] ?? '-', + $disk['media_type'] ?? '-', + $disk['bus_type'] ?? '-', + ], + $inventory['physical_disks'] + ), + ); + + info((string) __('messages.toolbox.network_subsection')); + table( + headers: [ + (string) __('messages.network.interface_headers.interface'), + (string) __('messages.network.interface_headers.ipv4'), + (string) __('messages.network.interface_headers.mac'), + (string) __('messages.network.interface_headers.status'), + ], + rows: array_map( + fn (array $iface): array => [ + $iface['interface'] ?? '-', + $iface['ipv4'] ?? '-', + $iface['mac'] ?? '-', + $iface['status'] ?? '-', + ], + $inventory['network_adapters'] + ), + ); + + $shouldExport = (bool) $this->option('export'); + if (! $shouldExport && $this->input->isInteractive()) { + $shouldExport = confirm( + label: (string) __('messages.toolbox.ask_export_inventory'), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + ); + } + + if ($shouldExport) { + return $this->exportInventorySheet($inventory, $locale); + } + + return self::SUCCESS; + } + + /** + * Map associative inventory fields into translated metric/value rows. + * + * @param array $fields + * @return array + */ + protected function formatMapRows(array $fields): array + { + $rows = []; + foreach ($fields as $key => $val) { + $labelKey = "messages.toolbox.fields.{$key}"; + $label = (string) __($labelKey); + if ($label === $labelKey) { + $label = ucfirst(str_replace('_', ' ', $key)); + } + $rows[] = [$label, (string) $val]; + } + + return $rows; + } + + /** + * Export the asset inventory profile into Markdown (.md) and JSON (.json) files. + * + * @param array $inventory + */ + protected function exportInventorySheet(array $inventory, string $locale): int + { + $dir = rtrim(getcwd() ?: base_path(), '/\\'); + $stamp = date('Y-m-d-His'); + $baseName = sprintf('it-toolbox-inventory-%s', $stamp); + $mdPath = $dir . DIRECTORY_SEPARATOR . $baseName . '.md'; + $jsonPath = $dir . DIRECTORY_SEPARATOR . $baseName . '.json'; + + $payload = [ + 'generated_at' => gmdate('Y-m-d\TH:i:s\Z'), + 'locale' => $locale, + 'os_family' => PHP_OS_FAMILY, + 'inventory' => $inventory, + ]; + + $mdLines = [ + sprintf('# %s — %s', (string) __('messages.app.name'), (string) __('messages.toolbox.inventory_section')), + '', + sprintf('## %s', (string) __('messages.toolbox.identity_subsection')), + '', + sprintf('| %s | %s |', (string) __('messages.common.metric'), (string) __('messages.common.value')), + '| :--- | :--- |', + ]; + + foreach ($this->formatMapRows((array) ($inventory['system_identity'] ?? [])) as [$k, $v]) { + $mdLines[] = sprintf('| %s | %s |', $k, $v); + } + + $mdLines[] = ''; + $mdLines[] = sprintf('## %s', (string) __('messages.toolbox.cpu_ram_subsection')); + $mdLines[] = ''; + $mdLines[] = sprintf('| %s | %s |', (string) __('messages.common.metric'), (string) __('messages.common.value')); + $mdLines[] = '| :--- | :--- |'; + + foreach ($this->formatMapRows((array) ($inventory['processor_memory'] ?? [])) as [$k, $v]) { + $mdLines[] = sprintf('| %s | %s |', $k, $v); + } + + $mdLines[] = ''; + + $mdOk = @file_put_contents($mdPath, implode("\n", $mdLines)) !== false; + $jsonOk = @file_put_contents($jsonPath, (string) json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) !== false; + + if (! $mdOk || ! $jsonOk) { + error((string) __('messages.report.exported_failed', ['path' => $mdPath])); + + return self::FAILURE; + } + + info((string) __('messages.report.exported_success', ['path' => $mdPath . ', ' . $jsonPath])); + + return self::SUCCESS; + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 8bb361c..95b4c14 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -68,8 +68,6 @@ public function handle(): int if ($choice === '1') { $this->executeSubcommand('health:check', $locale); - } elseif ($choice === '7') { - $this->executeSubcommand('report:export', $locale); } elseif ($choice === '8') { $this->executeSubcommand('self:update', $locale); } elseif ($choice === '9') { @@ -81,6 +79,7 @@ public function handle(): int '4' => 'network', '5' => 'maintenance', '6' => 'security', + '7' => 'reports', default => 'system', }; @@ -172,6 +171,8 @@ protected function handleCategorySubmenu(string $category, string $locale): void 'printers' => [ '1' => ['label' => (string) __('messages.menu.actions.printer_list'), 'command' => 'printer:list'], '2' => ['label' => (string) __('messages.menu.actions.printer_clear'), 'command' => 'printer:clear'], + '3' => ['label' => (string) __('messages.menu.actions.printer_test_page'), 'command' => 'printer:test-page'], + '4' => ['label' => (string) __('messages.menu.actions.printer_default'), 'command' => 'printer:default'], ], 'network' => [ '1' => ['label' => (string) __('messages.menu.actions.network_check'), 'command' => 'network:check'], @@ -198,6 +199,11 @@ protected function handleCategorySubmenu(string $category, string $locale): void '3' => ['label' => (string) __('messages.menu.actions.security_shares'), 'command' => 'security:shares'], '4' => ['label' => (string) __('messages.menu.actions.security_hosts'), 'command' => 'security:hosts'], ], + 'reports' => [ + '1' => ['label' => (string) __('messages.menu.actions.report_export'), 'command' => 'report:export'], + '2' => ['label' => (string) __('messages.menu.actions.toolbox_inventory'), 'command' => 'toolbox:inventory'], + '3' => ['label' => (string) __('messages.menu.actions.toolbox_benchmark'), 'command' => 'toolbox:benchmark'], + ], default => [], }; diff --git a/app/Contracts/SystemDriverInterface.php b/app/Contracts/SystemDriverInterface.php index 3fc6522..9a1f5d1 100644 --- a/app/Contracts/SystemDriverInterface.php +++ b/app/Contracts/SystemDriverInterface.php @@ -123,6 +123,22 @@ public function listPrinters(): array; */ public function clearPrintQueue(): ActionResult; + /** + * Send a test page to the specified printer. + * + * @param string $printerName + * @return ActionResult + */ + public function printTestPage(string $printerName): ActionResult; + + /** + * Set the system default printer. + * + * @param string $printerName + * @return ActionResult + */ + public function setDefaultPrinter(string $printerName): ActionResult; + /** * Retrieve active network interfaces, IPv4/IPv6, Gateway, DNS, and MAC addresses. * @@ -272,4 +288,25 @@ public function getNetworkShares(): array; * @return array */ public function inspectHostsFile(?string $customContent = null): array; + + /** + * Run a fast, zero-dependency CPU single-core and Disk sequential I/O micro-benchmark. + * + * @param int $diskSizeMb Temporary file size in MB (default 64 MB). + * @param float $cpuDurationSeconds Duration of the CPU SHA-256 loop in seconds (default 1.0s). + * @return ActionResult + */ + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult; + + /** + * Retrieve a complete corporate IT asset & hardware inventory profile (ready for GLPI / CMDB). + * + * @return array{ + * system_identity: array, + * processor_memory: array, + * physical_disks: array, + * network_adapters: array + * } + */ + public function getHardwareInventory(): array; } diff --git a/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php index 7b80bf4..4cafc89 100644 --- a/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php +++ b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php @@ -242,6 +242,88 @@ public function inspectHostsFile(?string $customContent = null): array return $entries; } + /** + * Run a fast, zero-dependency CPU single-core and Disk sequential I/O micro-benchmark. + */ + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult + { + $safeSizeMb = max(1, min(256, $diskSizeMb)); + $safeCpuSeconds = max(0.02, min(5.0, $cpuDurationSeconds)); + + // 1. CPU Single-Core Cryptographic SHA-256 Benchmark + $cpuDurationNs = (int) round($safeCpuSeconds * 1_000_000_000); + $cpuStartNs = hrtime(true); + $iterations = 0; + $seed = 'it-toolbox-cli-v2.0.0-benchmark'; + + while ((hrtime(true) - $cpuStartNs) < $cpuDurationNs) { + for ($i = 0; $i < 2500; $i++) { + $seed = hash('sha256', $seed . $i); + $iterations++; + } + } + + $cpuElapsedSec = max(0.001, (hrtime(true) - $cpuStartNs) / 1_000_000_000); + $opsPerSec = (int) round($iterations / $cpuElapsedSec); + + // 2. Disk Sequential Write & Read I/O Benchmark + $tempFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_bench_' . uniqid('', true) . '.tmp'; + $chunkSize = 1048576; // 1 MB + $chunkBuffer = str_repeat( hash('sha512', $seed, true), 16384 ); // 64 bytes * 16384 = 1 MB + + $writeSpeedMb = 0.0; + $readSpeedMb = 0.0; + + try { + $fpWrite = @fopen($tempFile, 'wb'); + if (is_resource($fpWrite)) { + $writeStartNs = hrtime(true); + for ($m = 0; $m < $safeSizeMb; $m++) { + @fwrite($fpWrite, $chunkBuffer, $chunkSize); + } + @fflush($fpWrite); + @fclose($fpWrite); + $writeElapsedSec = max(0.0001, (hrtime(true) - $writeStartNs) / 1_000_000_000); + $writeSpeedMb = round($safeSizeMb / $writeElapsedSec, 1); + } + + if (is_file($tempFile)) { + $fpRead = @fopen($tempFile, 'rb'); + if (is_resource($fpRead)) { + $readStartNs = hrtime(true); + while (! feof($fpRead)) { + @fread($fpRead, $chunkSize); + } + @fclose($fpRead); + $readElapsedSec = max(0.0001, (hrtime(true) - $readStartNs) / 1_000_000_000); + $readSpeedMb = round($safeSizeMb / $readElapsedSec, 1); + } + } + } finally { + if (is_file($tempFile)) { + @unlink($tempFile); + } + } + + $storageTier = match (true) { + $writeSpeedMb >= 350.0 => '🚀 NVMe / Fast SSD', + $writeSpeedMb >= 120.0 => '⚡ SATA SSD', + default => '🐢 HDD / Standard Storage', + }; + + return new ActionResult( + success: true, + message: 'messages.toolbox.benchmark_success', + details: [ + 'cpu_score' => sprintf('%s SHA-256 ops/sec', number_format($opsPerSec)), + 'disk_write_speed' => sprintf('%.1f MB/s (%d MB sample)', $writeSpeedMb, $safeSizeMb), + 'disk_read_speed' => sprintf('%.1f MB/s (%d MB sample)', $readSpeedMb, $safeSizeMb), + 'storage_tier' => $storageTier, + 'driver' => $this->getDriverLabel(), + ], + ); + } + /** * Calculate byte size of a cache file or directory tree safely. */ diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index d700962..f1af90c 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -1672,6 +1672,178 @@ public function getNetworkShares(): array return $shares; } + /** + * {@inheritDoc} + */ + public function printTestPage(string $printerName): ActionResult + { + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', trim($printerName)) ?? ''; + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.test_page_failed', + details: ['printer' => $printerName, 'driver' => 'Linux'], + ); + } + + $testBanner = implode("\n", [ + '====================================================', + ' IT TOOLBOX CLI - TEST PAGE ', + '====================================================', + 'Printer : ' . $cleanName, + 'Hostname : ' . (gethostname() ?: 'linux-host'), + 'Date/Time: ' . gmdate('Y-m-d H:i:s \U\T\C'), + 'Driver : CUPS / LinuxDriver', + '====================================================', + '', + ]); + + $tmpFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_testpage_' . uniqid() . '.txt'; + @file_put_contents($tmpFile, $testBanner); + + try { + $result = $this->processRunner->run(['lp', '-d', $cleanName, $tmpFile]); + } finally { + @unlink($tmpFile); + } + + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.printer.test_page_success', + details: [ + 'printer' => $cleanName, + 'output' => $result->output !== '' ? $result->output : 'Submitted to CUPS queue', + 'driver' => 'Linux', + ], + ); + } + + return new ActionResult( + success: false, + message: 'messages.printer.test_page_failed', + details: [ + 'printer' => $cleanName, + 'error' => $result->errorOutput ?: 'lp command failed', + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function setDefaultPrinter(string $printerName): ActionResult + { + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', trim($printerName)) ?? ''; + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.default_set_failed', + details: ['printer' => $printerName, 'driver' => 'Linux'], + ); + } + + $result = $this->processRunner->run(['lpoptions', '-d', $cleanName]); + + if ($this->isRoot() && $this->commandExists('lpadmin')) { + $this->processRunner->run(['lpadmin', '-d', $cleanName]); + } + + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.printer.default_set_success', + details: [ + 'printer' => $cleanName, + 'driver' => 'Linux', + ], + ); + } + + return new ActionResult( + success: false, + message: 'messages.printer.default_set_failed', + details: [ + 'printer' => $cleanName, + 'error' => $result->errorOutput ?: 'lpoptions command failed', + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getHardwareInventory(): array + { + $osInfo = $this->getOsInfo(); + $hwInfo = $this->getHardwareDiagnostics(); + $interfaces = $this->getNetworkInterfaces(); + + $vendor = trim((string) ($this->readFile('/sys/class/dmi/id/sys_vendor') ?? '')) ?: 'N/A'; + $product = trim((string) ($this->readFile('/sys/class/dmi/id/product_name') ?? '')) ?: 'N/A'; + $serial = trim((string) ($this->readFile('/sys/class/dmi/id/product_serial') ?? '')) ?: 'N/A'; + $biosVer = trim((string) ($this->readFile('/sys/class/dmi/id/bios_version') ?? '')) ?: 'N/A'; + $boardVendor = trim((string) ($this->readFile('/sys/class/dmi/id/board_vendor') ?? '')); + $boardName = trim((string) ($this->readFile('/sys/class/dmi/id/board_name') ?? '')); + $motherboard = trim($boardVendor . ' ' . $boardName) ?: 'N/A'; + + $physicalDisks = []; + $lsblkResult = $this->processRunner->run(['lsblk', '-d', '-b', '-o', 'NAME,SIZE,ROTA,TRAN,MODEL', '-J']); + if ($lsblkResult->successful && $lsblkResult->output !== '') { + $decoded = json_decode($lsblkResult->output, true); + foreach ((array) ($decoded['blockdevices'] ?? []) as $dev) { + if (! is_array($dev)) { + continue; + } + $name = (string) ($dev['name'] ?? ''); + if (str_starts_with($name, 'loop') || str_starts_with($name, 'ram') || str_starts_with($name, 'sr')) { + continue; + } + $rota = (bool) ($dev['rota'] ?? false); + $tran = strtoupper((string) ($dev['tran'] ?? 'SATA/NVMe')); + $mediaType = (! $rota || str_contains($name, 'nvme')) ? 'SSD / NVMe' : 'HDD (Rotational)'; + + $physicalDisks[] = [ + 'model' => trim((string) ($dev['model'] ?? ('/dev/' . $name))) ?: ('/dev/' . $name), + 'size' => $this->formatBytes((float) ($dev['size'] ?? 0.0)), + 'media_type' => $mediaType, + 'bus_type' => $tran !== '' ? $tran : 'Block', + ]; + } + } + + return [ + 'system_identity' => [ + 'hostname' => $osInfo['hostname'] ?? 'linux-host', + 'manufacturer' => $vendor, + 'model' => $product, + 'serial_number' => $serial, + 'bios_version' => $biosVer, + 'motherboard' => $motherboard, + 'os_edition' => $osInfo['os_name'] ?? 'Linux', + 'os_build' => sprintf('%s (%s)', $osInfo['os_version'] ?? '-', $osInfo['kernel'] ?? '-'), + ], + 'processor_memory' => [ + 'cpu_model' => $hwInfo['cpu_model'] ?? 'Unknown CPU', + 'cpu_cores' => $hwInfo['cpu_cores'] ?? 'N/A', + 'ram_total' => $hwInfo['ram_total'] ?? 'N/A', + 'ram_modules' => 'System Physical Memory (/proc/meminfo)', + ], + 'physical_disks' => $physicalDisks, + 'network_adapters' => array_map( + fn (array $iface): array => [ + 'interface' => $iface['interface'] ?? '-', + 'ipv4' => $iface['ipv4'] ?? '-', + 'mac' => $iface['mac'] ?? '-', + 'status' => $iface['status'] ?? '-', + ], + $interfaces + ), + ]; + } + /** * {@inheritDoc} */ diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 73d5c6f..451be0b 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -1457,6 +1457,196 @@ public function getNetworkShares(): array return $shares; } + /** + * {@inheritDoc} + */ + public function printTestPage(string $printerName): ActionResult + { + $cleanName = str_replace("'", "''", trim($printerName)); + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.test_page_failed', + details: ['printer' => $printerName, 'driver' => 'Windows'], + ); + } + + $script = sprintf( + <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$p = Get-CimInstance -ClassName Win32_Printer | Where-Object { $_.Name -eq '%s' } | Select-Object -First 1; +if ($null -eq $p) { + [PSCustomObject]@{ Success = $false; ReturnValue = -1; Error = 'Printer not found' } | ConvertTo-Json -Compress; + exit 0; +} +$res = Invoke-CimMethod -InputObject $p -MethodName PrintTestPage -ErrorAction SilentlyContinue; +$rv = if ($null -ne $res) { [int]$res.ReturnValue } else { -1 }; +[PSCustomObject]@{ + Success = ($rv -eq 0); + ReturnValue = $rv; + Error = if ($rv -eq 0) { '' } else { "WMI ReturnValue: $rv" } +} | ConvertTo-Json -Compress +PS, + $cleanName + ); + + $data = $this->runPowerShellJson($script); + $ok = ($data['Success'] ?? false) === true; + + return new ActionResult( + success: $ok, + message: $ok ? 'messages.printer.test_page_success' : 'messages.printer.test_page_failed', + details: [ + 'printer' => trim($printerName), + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function setDefaultPrinter(string $printerName): ActionResult + { + $cleanName = str_replace("'", "''", trim($printerName)); + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.default_set_failed', + details: ['printer' => $printerName, 'driver' => 'Windows'], + ); + } + + $script = sprintf( + <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$p = Get-CimInstance -ClassName Win32_Printer | Where-Object { $_.Name -eq '%s' } | Select-Object -First 1; +if ($null -eq $p) { + [PSCustomObject]@{ Success = $false; ReturnValue = -1; Error = 'Printer not found' } | ConvertTo-Json -Compress; + exit 0; +} +$res = Invoke-CimMethod -InputObject $p -MethodName SetDefaultPrinter -ErrorAction SilentlyContinue; +$rv = if ($null -ne $res) { [int]$res.ReturnValue } else { -1 }; +[PSCustomObject]@{ + Success = ($rv -eq 0); + ReturnValue = $rv; + Error = if ($rv -eq 0) { '' } else { "WMI ReturnValue: $rv" } +} | ConvertTo-Json -Compress +PS, + $cleanName + ); + + $data = $this->runPowerShellJson($script); + $ok = ($data['Success'] ?? false) === true; + + return new ActionResult( + success: $ok, + message: $ok ? 'messages.printer.default_set_success' : 'messages.printer.default_set_failed', + details: [ + 'printer' => trim($printerName), + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getHardwareInventory(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$cs = Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -First 1; +$bios = Get-CimInstance -ClassName Win32_BIOS | Select-Object -First 1; +$board = Get-CimInstance -ClassName Win32_BaseBoard | Select-Object -First 1; +$os = Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -First 1; +$cpu = Get-CimInstance -ClassName Win32_Processor | Select-Object -First 1; +$memModules = @(Get-CimInstance -ClassName Win32_PhysicalMemory | ForEach-Object { + $capGb = [Math]::Round(($_.Capacity / 1GB), 1); + "$($capGb)GB @ $($_.Speed)MHz" +}); +$disks = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Model = [string]$_.FriendlyName; + Size = [double]$_.Size; + MediaType = [string]$_.MediaType; + BusType = [string]$_.BusType + } +}); +if ($disks.Count -eq 0) { + $disks = @(Get-CimInstance -ClassName Win32_DiskDrive -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Model = [string]$_.Model; + Size = [double]$_.Size; + MediaType = [string]$_.MediaType; + BusType = [string]$_.InterfaceType + } + }); +} +[PSCustomObject]@{ + Hostname = [string]$cs.Name; + Manufacturer = [string]$cs.Manufacturer; + Model = [string]$cs.Model; + Domain = [string]$cs.Domain; + SerialNumber = [string]$bios.SerialNumber; + BiosVersion = [string]$bios.SMBIOSBIOSVersion; + Motherboard = [string]("$($board.Manufacturer) $($board.Product)".Trim()); + OsName = [string]$os.Caption; + OsBuild = [string]("$($os.Version) (Build $($os.BuildNumber))"); + CpuModel = [string]$cpu.Name; + CpuCores = [string]("$($cpu.NumberOfCores) Cores / $($cpu.NumberOfLogicalProcessors) Threads"); + TotalRamBytes = [double]($cs.TotalPhysicalMemory -as [double]); + RamModules = [string]($memModules -join ', '); + Disks = @($disks) +} | ConvertTo-Json -Compress -Depth 4 +PS; + + $data = $this->runPowerShellJson($script); + $interfaces = $this->getNetworkInterfaces(); + + $physicalDisks = []; + foreach ($this->normalizeJsonList((array) ($data['Disks'] ?? [])) as $d) { + if (! is_array($d)) { + continue; + } + $physicalDisks[] = [ + 'model' => trim((string) ($d['Model'] ?? 'Physical Disk')) ?: 'Physical Disk', + 'size' => $this->formatBytes((float) ($d['Size'] ?? 0.0)), + 'media_type' => trim((string) ($d['MediaType'] ?? 'SSD/HDD')) ?: 'SSD/HDD', + 'bus_type' => trim((string) ($d['BusType'] ?? 'SATA/NVMe')) ?: 'SATA/NVMe', + ]; + } + + return [ + 'system_identity' => [ + 'hostname' => trim((string) ($data['Hostname'] ?? (gethostname() ?: 'UNKNOWN'))), + 'manufacturer' => trim((string) ($data['Manufacturer'] ?? 'N/A')) ?: 'N/A', + 'model' => trim((string) ($data['Model'] ?? 'N/A')) ?: 'N/A', + 'serial_number' => trim((string) ($data['SerialNumber'] ?? 'N/A')) ?: 'N/A', + 'bios_version' => trim((string) ($data['BiosVersion'] ?? 'N/A')) ?: 'N/A', + 'motherboard' => trim((string) ($data['Motherboard'] ?? 'N/A')) ?: 'N/A', + 'os_edition' => trim((string) ($data['OsName'] ?? 'Windows')) ?: 'Windows', + 'os_build' => trim((string) ($data['OsBuild'] ?? 'N/A')) ?: 'N/A', + ], + 'processor_memory' => [ + 'cpu_model' => trim((string) ($data['CpuModel'] ?? 'Unknown CPU')) ?: 'Unknown CPU', + 'cpu_cores' => trim((string) ($data['CpuCores'] ?? 'N/A')) ?: 'N/A', + 'ram_total' => $this->formatBytes((float) ($data['TotalRamBytes'] ?? 0.0)), + 'ram_modules' => trim((string) ($data['RamModules'] ?? 'N/A')) ?: 'N/A', + ], + 'physical_disks' => $physicalDisks, + 'network_adapters' => array_map( + fn (array $iface): array => [ + 'interface' => $iface['interface'] ?? '-', + 'ipv4' => $iface['ipv4'] ?? '-', + 'mac' => $iface['mac'] ?? '-', + 'status' => $iface['status'] ?? '-', + ], + $interfaces + ), + ]; + } + /** * {@inheritDoc} */ diff --git a/config/app.php b/config/app.php index 56d2fb5..96f8e50 100644 --- a/config/app.php +++ b/config/app.php @@ -28,7 +28,7 @@ | */ - 'version' => '1.2.0', + 'version' => '2.0.0', /* |-------------------------------------------------------------------------- diff --git a/lang/en/messages.php b/lang/en/messages.php index 1901db8..ecf6170 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -36,7 +36,7 @@ 'network' => '🌐 Network & Connectivity Diagnostics', 'maintenance' => '🧹 System Maintenance & Cleanup', 'security' => '🛡 Security & Access Auditing', - 'reports' => '📄 Export Diagnostic Report', + 'reports' => '📄 Reports, Asset Inventory & Benchmark', 'self_update' => '⬆️ Check for Updates (self:update)', 'language' => '🌍 Switch Language (EN / PT-BR)', ], @@ -52,6 +52,8 @@ 'system_kill' => 'Force-Kill Frozen Process by PID, Name or List (system:kill)', 'printer_list' => 'List Installed Printers & Status (printer:list)', 'printer_clear' => 'Restart Spooler & Clear Print Queue (printer:clear)', + 'printer_test_page' => 'Send Diagnostic Test Page to Printer (printer:test-page)', + 'printer_default' => 'Set System Default Printer (printer:default)', 'network_check' => 'Interfaces & Connectivity Health Check (network:check)', 'network_flush' => 'Flush DNS Cache & Renew IP Lease (network:flush)', 'network_ports' => 'Inspect Open Listening Ports (network:ports)', @@ -72,6 +74,8 @@ 'security_shares' => 'Inspect Active Network Shares — SMB, Samba & NFS (security:shares)', 'security_hosts' => 'Audit System Hosts File & Custom Domain Redirects (security:hosts)', 'report_export' => 'Export Full System Diagnostic Report (report:export)', + 'toolbox_inventory' => 'Generate Hardware & IT Asset Inventory Sheet (toolbox:inventory)', + 'toolbox_benchmark' => 'Run CPU Single-Core & Disk I/O Benchmark (toolbox:benchmark)', ], ], @@ -101,6 +105,8 @@ 'killing_process' => 'Terminating process PID :pid...', 'printer_list' => 'Querying installed printers and spooler status...', 'printer_clear' => 'Stopping spooler, purging queue, and restarting service...', + 'printer_test_page' => 'Sending diagnostic test page to ":printer"...', + 'printer_default' => 'Setting ":printer" as the system default printer...', 'network_check' => 'Inspecting network interfaces and testing connectivity...', 'network_flush' => 'Flushing DNS resolver cache and renewing network lease...', 'network_ports' => 'Scanning active listening TCP/UDP ports...', @@ -121,6 +127,8 @@ 'security_shares' => 'Querying active SMB, Samba, and NFS network shares...', 'security_hosts' => 'Inspecting system hosts file for custom domain mappings...', 'report_export' => 'Generating full diagnostic report...', + 'toolbox_benchmark' => 'Running CPU SHA-256 and 64 MB sequential Disk I/O benchmark...', + 'toolbox_inventory' => 'Collecting hardware, BIOS serial, storage, and network inventory...', 'self_update_check' => 'Checking GitHub Releases for newer versions...', 'self_update_download' => 'Downloading and installing update v:version...', ], @@ -285,6 +293,14 @@ 'confirm_clear' => 'This will restart the Print Spooler / CUPS service and delete all pending print jobs. Proceed?', 'queue_cleared_success' => 'Print spooler restarted and pending print queue cleared successfully.', 'queue_cleared_failed' => 'Failed to clear print queue. Verify administrator/sudo permissions.', + 'test_page_section' => 'Printer Diagnostic Test Page', + 'select_printer_prompt' => 'Select the printer number to send a test page:', + 'test_page_success' => 'Diagnostic test page sent to the printer queue successfully.', + 'test_page_failed' => 'Failed to send test page to the selected printer.', + 'default_section' => 'System Default Printer Configuration', + 'select_default_prompt' => 'Select the printer number to set as system default:', + 'default_set_success' => 'Default printer updated successfully.', + 'default_set_failed' => 'Failed to update the system default printer.', ], 'network' => [ @@ -439,6 +455,42 @@ 'battery_health' => 'Battery Health & Wear', 'cycle_count' => 'Charge Cycle Count', 'browsers_cleaned' => 'Browsers Processed', + 'printer' => 'Target Printer', + 'cpu_score' => 'CPU Single-Core Score', + 'disk_write_speed' => 'Disk Sequential Write', + 'disk_read_speed' => 'Disk Sequential Read', + 'storage_tier' => 'Detected Storage Tier', + ], + ], + + 'toolbox' => [ + 'benchmark_section' => 'CPU Single-Core & Disk Sequential I/O Micro-Benchmark', + 'benchmark_success' => 'System CPU and Disk I/O micro-benchmark completed successfully.', + 'inventory_section' => 'Hardware & IT Asset Technical Inventory Sheet (GLPI / CMDB)', + 'identity_subsection' => 'System Identity, BIOS Serial & Operating System', + 'cpu_ram_subsection' => 'Processor & Physical Memory Modules', + 'disks_subsection' => 'Physical Storage Drives', + 'network_subsection' => 'Network Adapters & MAC Addresses', + 'ask_export_inventory' => 'Would you like to export this asset inventory sheet to Markdown (.md) and JSON (.json)?', + 'disk_headers' => [ + 'model' => 'Drive Model', + 'size' => 'Capacity', + 'media_type' => 'Media Type', + 'bus_type' => 'Interface / Bus', + ], + 'fields' => [ + 'hostname' => 'Hostname', + 'manufacturer' => 'Manufacturer', + 'model' => 'System Model', + 'serial_number' => 'BIOS / Chassis Serial Number', + 'bios_version' => 'BIOS / Firmware Version', + 'motherboard' => 'Motherboard', + 'os_edition' => 'OS Edition', + 'os_build' => 'OS Build / Kernel', + 'cpu_model' => 'Processor Model', + 'cpu_cores' => 'Cores / Threads', + 'ram_total' => 'Total Physical RAM', + 'ram_modules' => 'Memory Modules / Slots', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 84176b8..d365d72 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -36,7 +36,7 @@ 'network' => '🌐 Rede & Conectividade', 'maintenance' => '🧹 Limpeza & Manutenção', 'security' => '🛡 Segurança & Auditoria de Acesso', - 'reports' => '📄 Exportar Relatório de Atendimento', + 'reports' => '📄 Relatórios, Inventário & Benchmark', 'self_update' => '⬆️ Verificar Atualizações (self:update)', 'language' => '🌍 Alterar Idioma (EN / PT-BR)', ], @@ -52,6 +52,8 @@ 'system_kill' => 'Encerrar Processo Travado por PID, Nome ou Lista (system:kill)', 'printer_list' => 'Listar Impressoras Instaladas e Status (printer:list)', 'printer_clear' => 'Reiniciar Spooler e Limpar Fila de Impressão (printer:clear)', + 'printer_test_page' => 'Enviar Página de Teste para Impressora (printer:test-page)', + 'printer_default' => 'Definir Impressora Padrão do Sistema (printer:default)', 'network_check' => 'Interfaces e Teste de Saúde de Conectividade (network:check)', 'network_flush' => 'Limpar Cache DNS e Renovar Concessão de IP (network:flush)', 'network_ports' => 'Inspecionar Portas Abertas em Escuta (network:ports)', @@ -72,6 +74,8 @@ 'security_shares' => 'Inspecionar Compartilhamentos Ativos — SMB, Samba e NFS (security:shares)', 'security_hosts' => 'Auditar Arquivo Hosts e Redirecionamentos de Domínio (security:hosts)', 'report_export' => 'Exportar Relatório Completo de Diagnóstico (report:export)', + 'toolbox_inventory' => 'Gerar Ficha Técnica de Inventário Patrimonial (toolbox:inventory)', + 'toolbox_benchmark' => 'Executar Benchmark Rápido de CPU & Disco (toolbox:benchmark)', ], ], @@ -101,6 +105,8 @@ 'killing_process' => 'Encerrando processo PID :pid...', 'printer_list' => 'Consultando impressoras instaladas e status do spooler...', 'printer_clear' => 'Parando spooler, limpando fila e reiniciando serviço...', + 'printer_test_page' => 'Enviando página de teste diagnóstica para ":printer"...', + 'printer_default' => 'Definindo ":printer" como impressora padrão do sistema...', 'network_check' => 'Inspecionando interfaces de rede e testando conectividade...', 'network_flush' => 'Limpando cache de resolução DNS e renovando IP...', 'network_ports' => 'Escaneando portas TCP/UDP ativas em escuta...', @@ -121,6 +127,8 @@ 'security_shares' => 'Consultando compartilhamentos de rede SMB, Samba e NFS ativos...', 'security_hosts' => 'Inspecionando arquivo hosts do sistema por mapeamentos customizados...', 'report_export' => 'Gerando relatório completo de diagnóstico...', + 'toolbox_benchmark' => 'Executando benchmark rápido de CPU SHA-256 e I/O sequencial de 64 MB...', + 'toolbox_inventory' => 'Coletando inventário completo de hardware, BIOS, discos e rede...', 'self_update_check' => 'Consultando GitHub Releases por novas versões...', 'self_update_download' => 'Baixando e instalando atualização v:version...', ], @@ -285,6 +293,14 @@ 'confirm_clear' => 'Isto reiniciará o serviço Spooler de Impressão / CUPS e removerá todos os trabalhos pendentes. Deseja prosseguir?', 'queue_cleared_success' => 'Spooler de impressão reiniciado e fila pendente limpa com sucesso.', 'queue_cleared_failed' => 'Falha ao limpar a fila de impressão. Verifique permissões de Administrador/sudo.', + 'test_page_section' => 'Impressão de Página de Teste Diagnóstica', + 'select_printer_prompt' => 'Selecione o número da impressora para enviar a página de teste:', + 'test_page_success' => 'Página de teste diagnóstica enviada para a fila da impressora com sucesso.', + 'test_page_failed' => 'Falha ao enviar página de teste para a impressora selecionada.', + 'default_section' => 'Configuração de Impressora Padrão do Sistema', + 'select_default_prompt' => 'Selecione o número da impressora para definir como padrão:', + 'default_set_success' => 'Impressora padrão atualizada com sucesso.', + 'default_set_failed' => 'Falha ao atualizar a impressora padrão do sistema.', ], 'network' => [ @@ -439,6 +455,42 @@ 'battery_health' => 'Saúde e Desgaste da Bateria', 'cycle_count' => 'Contagem de Ciclos', 'browsers_cleaned' => 'Navegadores Processados', + 'printer' => 'Impressora Alvo', + 'cpu_score' => 'Score CPU Single-Core', + 'disk_write_speed' => 'Escrita Sequencial em Disco', + 'disk_read_speed' => 'Leitura Sequencial em Disco', + 'storage_tier' => 'Perfil de Armazenamento Detectado', + ], + ], + + 'toolbox' => [ + 'benchmark_section' => 'Micro-Benchmark de CPU Single-Core & I/O Sequencial de Disco', + 'benchmark_success' => 'Micro-benchmark de CPU e I/O de disco concluído com sucesso.', + 'inventory_section' => 'Ficha Técnica de Inventário Patrimonial & Hardware (GLPI / CMDB)', + 'identity_subsection' => 'Identidade do Equipamento, Serial BIOS & Sistema Operacional', + 'cpu_ram_subsection' => 'Processador & Módulos de Memória Física', + 'disks_subsection' => 'Unidades Físicas de Armazenamento', + 'network_subsection' => 'Adaptadores de Rede & Endereços MAC', + 'ask_export_inventory' => 'Deseja exportar esta ficha de inventário patrimonial em Markdown (.md) e JSON (.json)?', + 'disk_headers' => [ + 'model' => 'Modelo do Disco', + 'size' => 'Capacidade', + 'media_type' => 'Tipo de Mídia', + 'bus_type' => 'Interface / Barramento', + ], + 'fields' => [ + 'hostname' => 'Nome do Host', + 'manufacturer' => 'Fabricante', + 'model' => 'Modelo do Equipamento', + 'serial_number' => 'Número de Série (BIOS / Chassi)', + 'bios_version' => 'Versão da BIOS / Firmware', + 'motherboard' => 'Placa-Mãe', + 'os_edition' => 'Edição do SO', + 'os_build' => 'Build / Kernel do SO', + 'cpu_model' => 'Modelo do Processador', + 'cpu_cores' => 'Núcleos / Threads', + 'ram_total' => 'RAM Física Total', + 'ram_modules' => 'Módulos / Slots de Memória', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index 18805bd..9271c2b 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -231,6 +231,31 @@ public function inspectHostsFile(?string $customContent = null): array { return []; } + + public function printTestPage(string $printerName): ActionResult + { + return new ActionResult(true, 'messages.printer.test_page_success'); + } + + public function setDefaultPrinter(string $printerName): ActionResult + { + return new ActionResult(true, 'messages.printer.default_set_success'); + } + + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult + { + return new ActionResult(true, 'messages.toolbox.benchmark_success'); + } + + public function getHardwareInventory(): array + { + return [ + 'system_identity' => [], + 'processor_memory' => [], + 'physical_disks' => [], + 'network_adapters' => [], + ]; + } }; $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_test_' . uniqid(); diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php index 45012dd..9a768f9 100644 --- a/tests/Unit/HealthCheckServiceTest.php +++ b/tests/Unit/HealthCheckServiceTest.php @@ -223,6 +223,31 @@ public function inspectHostsFile(?string $customContent = null): array { return []; } + + public function printTestPage(string $printerName): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function setDefaultPrinter(string $printerName): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getHardwareInventory(): array + { + return [ + 'system_identity' => [], + 'processor_memory' => [], + 'physical_disks' => [], + 'network_adapters' => [], + ]; + } }; } diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index a492779..a3f2055 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -379,3 +379,84 @@ public function getEffectiveUid(): int ->and($shares[0]['type'])->toBe('Samba (SMB)') ->and($shares[1]['type'])->toBe('NFS Export'); }); + +it('handles Linux CUPS test page, default printer, CPU/Disk micro-benchmark, and DMI hardware inventory', function (): void { + $executor = new class implements ProcessExecutorInterface + { + /** @var array */ + public array $files = [ + '/etc/os-release' => "PRETTY_NAME=\"Ubuntu 24.04.1 LTS\"\nVERSION=\"24.04\"\n", + '/proc/sys/kernel/hostname' => "ubuntu-asset-01\n", + '/proc/uptime' => "3600.00 7200.00\n", + '/proc/cpuinfo' => "processor\t: 0\nmodel name\t: AMD Ryzen 9 7950X\ncpu cores\t: 16\n", + '/proc/loadavg' => "0.15 0.10 0.05 1/100 500\n", + '/proc/meminfo' => "MemTotal: 33554432 kB\nMemAvailable: 25165824 kB\n", + '/etc/resolv.conf' => "nameserver 1.1.1.1\n", + '/sys/class/dmi/id/sys_vendor' => "LENOVO\n", + '/sys/class/dmi/id/product_name' => "ThinkPad P16 Gen 2\n", + '/sys/class/dmi/id/product_serial' => "PF4X9988\n", + '/sys/class/dmi/id/bios_version' => "N3XET50W\n", + '/sys/class/dmi/id/board_vendor' => "LENOVO\n", + '/sys/class/dmi/id/board_name' => "21FA0011BR\n", + ]; + + public function run(array $command, int $timeout = 30): ProcessResult + { + if ($command[0] === 'lp') { + return new ProcessResult(0, 'request id is Office_CUPS-77 (1 file(s))'); + } + + return match ($command) { + ['lpoptions', '-d', 'Office_CUPS'] => new ProcessResult(0, ''), + ['uname', '-r'] => new ProcessResult(0, '6.8.0-45-generic'), + ['uname', '-m'] => new ProcessResult(0, 'x86_64'), + ['ip', '-j', 'route'] => new ProcessResult(0, json_encode([['dst' => 'default', 'gateway' => '192.168.1.1', 'dev' => 'eth0']])), + ['ip', '-j', 'addr'] => new ProcessResult(0, json_encode([[ + 'ifname' => 'eth0', + 'operstate' => 'UP', + 'address' => 'aa:bb:cc:dd:ee:ff', + 'addr_info' => [['family' => 'inet', 'local' => '192.168.1.50', 'prefixlen' => 24]], + ]])), + ['lsblk', '-d', '-b', '-o', 'NAME,SIZE,ROTA,TRAN,MODEL', '-J'] => new ProcessResult(0, json_encode([ + 'blockdevices' => [ + ['name' => 'nvme0n1', 'size' => 1024209543168, 'rota' => false, 'tran' => 'nvme', 'model' => 'WD Black SN850X 1TB'], + ], + ])), + default => new ProcessResult(1, '', '', false), + }; + } + + public function readFile(string $path): ?string + { + return $this->files[$path] ?? null; + } + + public function getEffectiveUid(): int + { + return 1000; + } + }; + + $driver = new LinuxDriver($executor); + + $testPage = $driver->printTestPage('Office_CUPS'); + expect($testPage->success)->toBeTrue() + ->and($testPage->message)->toBe('messages.printer.test_page_success'); + + $defaultSet = $driver->setDefaultPrinter('Office_CUPS'); + expect($defaultSet->success)->toBeTrue() + ->and($defaultSet->message)->toBe('messages.printer.default_set_success'); + + $inventory = $driver->getHardwareInventory(); + expect($inventory['system_identity']['hostname'])->toBe('ubuntu-asset-01') + ->and($inventory['system_identity']['manufacturer'])->toBe('LENOVO') + ->and($inventory['system_identity']['serial_number'])->toBe('PF4X9988') + ->and($inventory['processor_memory']['ram_total'])->toBe('32.00 GB') + ->and($inventory['physical_disks'])->toHaveCount(1) + ->and($inventory['physical_disks'][0]['media_type'])->toBe('SSD / NVMe'); + + $bench = $driver->runSystemBenchmark(1, 0.05); + expect($bench->success)->toBeTrue() + ->and($bench->message)->toBe('messages.toolbox.benchmark_success') + ->and($bench->details['cpu_score'])->toContain('SHA-256 ops/sec'); +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index cf61795..854853c 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -525,3 +525,89 @@ public function getEffectiveUid(): int @rmdir($tempDir); } }); + +it('handles Windows printer test page, default printer, CPU/Disk micro-benchmark, and hardware asset inventory', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $callIndex = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + $this->callIndex++; + + return match ($this->callIndex) { + 1 => new ProcessResult(0, (string) json_encode(['Success' => true, 'ReturnValue' => 0, 'Error' => ''])), + 2 => new ProcessResult(0, (string) json_encode(['Success' => true, 'ReturnValue' => 0, 'Error' => ''])), + 3 => new ProcessResult(0, (string) json_encode([ + 'Hostname' => 'ASSET-WS-042', + 'Manufacturer' => 'Dell Inc.', + 'Model' => 'OptiPlex 7010', + 'SerialNumber' => 'SN-99887766', + 'BiosVersion' => '1.18.0', + 'Motherboard' => 'Dell Inc. 0X88Y', + 'OsName' => 'Microsoft Windows 11 Pro', + 'OsBuild' => '10.0.22631 (Build 22631)', + 'CpuModel' => 'Intel(R) Core(TM) i7-13700', + 'CpuCores' => '16 Cores / 24 Threads', + 'TotalRamBytes' => 34359738368, // 32 GB + 'RamModules' => '16.0GB @ 4800MHz, 16.0GB @ 4800MHz', + 'Disks' => [ + [ + 'Model' => 'Samsung PM9A1 NVMe 512GB', + 'Size' => 512110190592, + 'MediaType' => 'SSD', + 'BusType' => 'NVMe', + ], + ], + ])), + 4 => new ProcessResult(0, (string) json_encode([ + [ + 'InterfaceAlias' => 'Ethernet', + 'IPv4' => '10.0.10.42', + 'IPv6' => '', + 'Gateway' => '10.0.10.1', + 'DnsServers' => '10.0.10.2', + 'MacAddress' => '00-1A-2B-3C-4D-5E', + 'Status' => 'Up', + ], + ])), + default => new ProcessResult(0, '[]'), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $testPage = $driver->printTestPage('HP LaserJet M428'); + expect($testPage->success)->toBeTrue() + ->and($testPage->message)->toBe('messages.printer.test_page_success'); + + $defaultSet = $driver->setDefaultPrinter('HP LaserJet M428'); + expect($defaultSet->success)->toBeTrue() + ->and($defaultSet->message)->toBe('messages.printer.default_set_success'); + + $inventory = $driver->getHardwareInventory(); + expect($inventory['system_identity']['hostname'])->toBe('ASSET-WS-042') + ->and($inventory['system_identity']['serial_number'])->toBe('SN-99887766') + ->and($inventory['processor_memory']['ram_total'])->toBe('32.00 GB') + ->and($inventory['physical_disks'])->toHaveCount(1) + ->and($inventory['physical_disks'][0]['bus_type'])->toBe('NVMe') + ->and($inventory['network_adapters'][0]['mac'])->toBe('00-1A-2B-3C-4D-5E'); + + $bench = $driver->runSystemBenchmark(1, 0.05); + expect($bench->success)->toBeTrue() + ->and($bench->message)->toBe('messages.toolbox.benchmark_success') + ->and($bench->details['cpu_score'])->toContain('SHA-256 ops/sec') + ->and($bench->details['disk_write_speed'])->toContain('MB/s') + ->and($bench->details['disk_read_speed'])->toContain('MB/s'); +});