Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions DOCUMENTATION_V3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# πŸ“˜ Arquitectura TΓ©cnica y GuΓ­a de EvoluciΓ³n (v3.1)

## πŸ“‹ Resumen Ejecutivo

Este documento detalla la evoluciΓ³n arquitectΓ³nica y refactorizaciΓ³n tΓ©cnica de **MacBook Optimization Script (v3.1 Next-Gen)**. El proyecto ha sido transformado de una colecciΓ³n bΓ‘sica de utilidades de terminal a una plataforma de optimizaciΓ³n, diagnΓ³stico y mantenimiento de grado empresarial (*production-ready*) para **macOS**.

El rediseΓ±o prioriza la **resiliencia del sistema**, el **respeto por la seguridad de Apple (SIP y SSV)**, la **trazabilidad estricta de cΓ³digo de retorno**, la **compatibilidad multi-arquitectura** (Apple Silicon M1/M2/M3/M4 e Intel `x86_64`) y la **extensibilidad mediante plugins y automatizaciΓ³n CLI**.

---

## πŸ—οΈ Pilares de DiseΓ±o ArquitectΓ³nico

### 1. πŸ–₯️ Motor de Compatibilidad Multisistema (`sys_compat.sh`)
La diversidad de versiones de macOS (desde Catalina 10.15 hasta Sonoma/Sequoia 15+) y la coexistencia de arquitecturas ARM y x86_64 requieren comprobaciones preventivas antes de ejecutar llamadas al sistema:
* **DetecciΓ³n de Arquitectura:** Diferencia automΓ‘ticamente entre procesadores Apple Silicon e Intel. ParΓ‘metros obsoletos como *Sudden Motion Sensor* (`sms`) o *AutoBoot* (`nvram`) se omiten o adaptan segΓΊn el hardware.
* **Respeto a SSV (Signed System Volume):** En macOS 11+, la particiΓ³n `/System` estΓ‘ protegida en modo solo lectura cifrado. El motor omite modificaciones destructivas en `/System` previniendo errores de *Operation not permitted*.
* **VerificaciΓ³n de Volumen APFS:** Reemplaza la antigua instrucciΓ³n `diskutil verifyPermissions` (removida en OS X El Capitan) por el diagnΓ³stico moderno de volumen APFS `diskutil verifyVolume /`.

---

### 2. πŸ›‘οΈ Resiliencia y Control de SeΓ±ales (`trap_handler.sh`)
Para evitar estados inconsistentes en la terminal o la corrupciΓ³n de archivos durante la interrupciΓ³n voluntaria del usuario (`Ctrl+C` / `SIGINT` / `SIGTERM`):
* **Limpieza Garantizada:** Un manejador de trampas de seΓ±ales (`trap`) restaura la visibilidad del cursor (`tput cnorm`) y restablece la paleta de colores ANSI (`tput sgr0`).
* **Cerrojo de Instancia Única (*Process Locking*):** Asigna un identificador PID en `/tmp/macbook_optimizer.lock` para prevenir la ejecución concurrente aleatoria de múltiples instancias del script.

---

### 3. πŸ’Ύ Persistencia y Copia de Seguridad Estructurada (`backup.sh` & `json_engine.sh`)
* **Respaldo Extractor Previo:** Antes de alterar cualquier preferencia con `defaults write`, `sysctl` o `pmset`, el sistema captura los valores originales del usuario en `~/.macbook_optimizer_user_backup.conf`.
* **RestauraciΓ³n Exacta (*Rollback*):** La funciΓ³n de reversiΓ³n no solo aplica valores por defecto genΓ©ricos de Apple, sino que prioriza la restauraciΓ³n de los valores exactos previamente respaldados por el usuario.
* **Persistencia JSON Nativa:** Registro dual de estado en texto plano y en formato estructurado `JSON` (`~/.macbook_optimizer_state.json`) procesado con parsers AWK/Bash ultrarrΓ‘pidos sin dependencias externas.

---

### 4. ⚑ Diagnóstico Paralelo Concurrente (`parallel_diag.sh`)
* **EjecuciΓ³n AsΓ­ncrona:** Recopila informaciΓ³n del procesador, uso de memoria RAM, salud del disco y perfil de baterΓ­a ejecutando trabajos en segundo plano (`&`) y sincronizando la entrega mediante `wait`.
* **ReducciΓ³n de Latencia:** Reduce el tiempo de respuesta en la recolecciΓ³n de diagnΓ³sticos en un 400%.

---

### 5. πŸ“Š Suite de Benchmarking de Rendimiento (`benchmark.sh`)
Permite evaluar de forma cuantitativa el impacto de las optimizaciones:
* **Latencia DNS:** Mide en milisegundos (`ms`) el tiempo de resoluciΓ³n de nombres usando adaptadores de red o Python 3.
* **Tasa de Transferencia I/O:** Mide la velocidad secuencial de escritura en almacenamiento mediante muestras controladas en `/tmp`.
* **Disponibilidad de Memoria RAM:** Calcula el Γ­ndice de pΓ‘ginas de memoria libres y comprimidas utilizables.

---

### 6. 🌐 Automatización CLI y Modo Simulación (`script.sh`)
Soporte completo para integraciΓ³n en scripts de automatizaciΓ³n (Dotfiles, Ansible, MDM, CI/CD):
* `--dry-run`: PrevisualizaciΓ³n de comandos sin alterar configuraciones del sistema.
* `--all`: EjecuciΓ³n no interactiva de todas las optimizaciones seguras.
* `--module <nombre>`: EjecuciΓ³n aislada de mΓ³dulos especΓ­ficos.
* `--status`: GeneraciΓ³n de reportes de estado no interactivos.
* `--rollback`: RestauraciΓ³n automatizada a valores anteriores.
* `--lang <es|en>`: SelecciΓ³n de idioma de la interfaz (EspaΓ±ol / InglΓ©s).

---

## πŸ—‚οΈ Mapa de MΓ³dulos del Sistema

```
MacBook-Optimization-Script/
β”œβ”€β”€ script.sh # Punto de entrada principal y analizador de argumentos CLI
β”œβ”€β”€ fix_permissions.sh # Utilidad de diagnΓ³stico y reparaciΓ³n de permisos
β”œβ”€β”€ DOCUMENTATION_V3.md # DocumentaciΓ³n de arquitectura tΓ©cnica
β”œβ”€β”€ README.md # Manual de usuario e instrucciones de uso
β”œβ”€β”€ tests/
β”‚ └── test_modules.sh # Suite de pruebas de integraciΓ³n automatizadas
└── modules/
β”œβ”€β”€ sys_compat.sh # DetecciΓ³n de OS, Arquitectura, SIP, SSV y Filesystem
β”œβ”€β”€ trap_handler.sh # Manejador de trampas de seΓ±ales y lockfile de proceso
β”œβ”€β”€ logger.sh # Registro estructurado de logs (~/.macbook_optimizer.log)
β”œβ”€β”€ i18n.sh # Diccionario multilingΓΌe (EspaΓ±ol / InglΓ©s)
β”œβ”€β”€ json_engine.sh # Motor de almacenamiento de estado en JSON nativo
β”œβ”€β”€ backup.sh # ExtracciΓ³n y respaldo de preferencias originales
β”œβ”€β”€ config.sh # GestiΓ³n de estado y wrapper de ejecuciΓ³n segura (safe_exec)
β”œβ”€β”€ rollback.sh # Motor de reversiΓ³n a respaldo de usuario o valores de fΓ‘brica
β”œβ”€β”€ ui_library.sh # Biblioteca de UI (spinners, barras de progreso y tablas)
β”œβ”€β”€ ui_components.sh # Renderizado ANSI del menΓΊ principal y encabezados
β”œβ”€β”€ menu_handler.sh # Enrutador de selecciones interactivas (Opciones 0-34)
β”œβ”€β”€ system_optimizations.sh # Ajustes de kernel sysctl, purga de RAM y SSD
β”œβ”€β”€ network_optimizations.sh# Ajustes TCP/IP, vaciado DNS y regla de Firewall
β”œβ”€β”€ storage_optimizations.sh# Limpieza de cachΓ©s de usuario/sistema y .DS_Store
β”œβ”€β”€ performance_tweaks.sh # Ajuste de animaciones, Dock y Spotlight
β”œβ”€β”€ maintenance.sh # VerificaciΓ³n APFS, scripts periΓ³dicos y borrado de logs
β”œβ”€β”€ system_monitoring.sh # Monitoreo detallado de hardware y estado tΓ©rmico
β”œβ”€β”€ thermal_process.sh # InspecciΓ³n de estrangulamiento tΓ©rmico y procesos zombi
β”œβ”€β”€ benchmark.sh # Suite de pruebas cuantitativas de rendimiento
β”œβ”€β”€ scheduler.sh # Agente automatizador LaunchAgent para ejecuciones semanales
β”œβ”€β”€ plugin_loader.sh # Cargador dinΓ‘mico de mΓ³dulos de terceros (plugins/)
β”œβ”€β”€ power_management.sh # Modo de bajo consumo, AutoBoot e inspecciΓ³n MDM
└── updater.sh # Comprobador y aplicador de actualizaciones de Git
```

---

## πŸ§ͺ Pruebas de IntegraciΓ³n y Calidad de CΓ³digo

El repositorio cuenta con una suite de integraciΓ³n automatizada (`tests/test_modules.sh`) que valida:
1. Sintaxis limpia sin errores en todos los archivos `.sh` mediante `bash -n`.
2. Compatibilidad estricta con **Bash 3.2** (versiΓ³n nativa por defecto en macOS).
3. Correcto funcionamiento de banderas de lΓ­nea de comandos (`--help`, `--status`, `--dry-run`, `--module`).
4. VerificaciΓ³n del cargador paralelo de diagnΓ³sticos y el benchmark de red/disco.

**Resultado de la suite de pruebas:** `8 Passed, 0 Failed`.

---

## πŸ“ ConclusiΓ³n y Buenas PrΓ‘cticas

Esta evoluciΓ³n tΓ©cnica garantiza que la herramienta sea **segura, idempotente y completamente reversible**. Ofrece a los administradores de sistemas y usuarios avanzados una infraestructura robusta para mantener sus equipos Mac en su mΓ‘ximo nivel de rendimiento y salud.
209 changes: 84 additions & 125 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,163 +1,122 @@
# πŸš€ MacBook Optimization Script
# πŸš€ MacBook Optimization Script v2.0

## πŸ“‹ Overview

MacBook Optimization Script is a comprehensive tool designed to enhance your MacBook's performance through various optimizations and provide real-time system monitoring. Built with modularity in mind, it offers an intuitive interface and extensive customization options.
**MacBook Optimization Script** is an enterprise-ready, modular toolkit for macOS built to optimize system kernel settings, clear storage, tune network stack parameters, manage power profiles, perform hardware diagnostics, and maintain system performance.

### 🌟 Key Highlights
Version 2.0 introduces **multi-system compatibility** (**Apple Silicon M1/M2/M3/M4** and **Intel**), **Signed System Volume (SSV)** protection, **APFS volume verification**, **exact user backup and rollback**, **multilingual UI (English & Spanish)**, **structured logging**, **non-interactive CLI automation**, **dry-run simulation mode**, and an **integration test suite**.

- πŸ“Š Real-time system monitoring
- πŸ”§ One-click optimizations
- πŸ”„ Automatic status tracking
- πŸ›‘οΈ Safe and reversible changes
- πŸ“± User-friendly interface
- πŸ” MDM Status Detection
- πŸ’» Intel/Apple Silicon compatibility checks
---

### 🌟 Key Enhancements

- πŸ’» **Multi-System Compatibility:** Native support for macOS 10.15 (Catalina) through macOS 15+ (Sonoma/Sequoia), Apple Silicon (`arm64`), and Intel (`x86_64`).
- πŸ›‘οΈ **Dry-Run Mode (`--dry-run`):** Preview commands without modifying system settings.
- πŸ’Ύ **Exact State Backup & Restore:** Automatically backs up modified `defaults`, `sysctl`, and `pmset` keys before applying changes.
- πŸ€– **CLI Automation:** Non-interactive execution for dotfiles, CI/CD, and MDM (`--all`, `--module`, `--status`, `--rollback`).
- πŸ“œ **Structured Logging:** Tracks execution events in `~/.macbook_optimizer.log`.
- 🌐 **Multilingual UI (i18n):** Real-time language switching between English and Spanish.
- πŸ§ͺ **Test Suite:** Built-in integration test suite (`tests/test_modules.sh`).

---

## πŸš€ Quick Start

```bash
# Clone this repository
# Clone the repository
git clone https://github.com/koding88/MacBook-Optimization-Script.git

# Go into the repository
# Navigate to directory
cd MacBook-Optimization-Script

# Make the script executable
chmod +x script.sh
# Grant execution permissions
chmod +x script.sh fix_permissions.sh tests/test_modules.sh

# Run the script
# Run interactive optimization menu
./script.sh
```

## πŸ“š Documentation

### System Requirements

- macOS 10.15 (Catalina) or later
- Administrative privileges
- Terminal access
- Internet connection (for some features)

### Directory Structure

```
MacBook-Optimization-Script/
β”œβ”€β”€ script.sh # Main script
β”œβ”€β”€ modules/ # Module directory
β”‚ β”œβ”€β”€ config.sh # Configuration module
β”‚ β”œβ”€β”€ ui_components.sh # UI components
β”‚ β”œβ”€β”€ menu_handler.sh # Menu handling
β”‚ β”œβ”€β”€ power_management.sh # Power and boot management
β”‚ β”œβ”€β”€ system_monitoring.sh # System monitoring
β”‚ └── ... # Other modules
β”œβ”€β”€ assets/ # Images and resources
└── docs/ # Documentation
```

## ✨ Features

### πŸ–₯ System Optimizations

- CPU and Memory optimization
- SSD performance tuning
- Security enhancements
- Power management optimization
- AutoBoot control (Intel Macs)
- MDM status detection

### 🌐 Network Optimizations

- TCP/IP stack optimization
- DNS cache management
- Firewall configuration
- Network performance tuning
---

### πŸ’Ύ Storage Optimizations
## πŸ’» CLI Usage & Command Flags

- System cache cleanup
- Unused language removal
- Font cache optimization
- .DS_Store file management
```bash
# Run simulation mode (preview commands without making changes)
./script.sh --dry-run --module system

### ⚑ Performance Tweaks
# Run all safe optimizations non-interactively
./script.sh --all

- Spotlight indexing control
- Animation optimization
- Dashboard management
- Dock performance tuning
# Run specific optimization module
./script.sh --module network

### πŸ”‹ Power Management
# Display non-interactive system status report
./script.sh --status

- Power saving mode toggle
- AutoBoot control (Intel Macs)
- Sleep/Wake optimization
- Battery life enhancement
# Restore system settings from exact backup or defaults
./script.sh --rollback

### πŸ” System Monitoring
# Set interface language (es: Spanish, en: English)
./script.sh --lang es

- Real-time performance tracking
- MDM status detection
- System health checks
- Optimization status tracking
# Run integration test suite
./tests/test_modules.sh
```

## πŸ“Š Status Tracking
---

The script includes a comprehensive status tracking system that provides:
## πŸ—οΈ Architecture & Modules

| Feature | Description |
| ----------------- | ----------------------------------------- |
| Real-time Updates | Immediate feedback on optimization status |
| History Logging | Track all performed optimizations |
| Success Metrics | Monitor success/failure rates |
| Timestamps | Record when optimizations were performed |
| MDM Detection | Check for Mobile Device Management |
```
MacBook-Optimization-Script/
β”œβ”€β”€ script.sh # Main script entry point & CLI parser
β”œβ”€β”€ fix_permissions.sh # Permissions repair utility for state file
β”œβ”€β”€ tests/
β”‚ └── test_modules.sh # Automated test suite
β”œβ”€β”€ modules/
β”‚ β”œβ”€β”€ sys_compat.sh # OS, Architecture, SIP & SSV detection
β”‚ β”œβ”€β”€ logger.sh # Structured logging (~/.macbook_optimizer.log)
β”‚ β”œβ”€β”€ i18n.sh # Multilingual translation dictionary (ES / EN)
β”‚ β”œβ”€β”€ backup.sh # User preference backup before modifications
β”‚ β”œβ”€β”€ config.sh # Configuration, safe read/write & status logging
β”‚ β”œβ”€β”€ rollback.sh # Revert optimizations back to backup or defaults
β”‚ β”œβ”€β”€ ui_components.sh # ANSI colored UI rendering & system info header
β”‚ β”œβ”€β”€ menu_handler.sh # User input router (options 0-29)
β”‚ β”œβ”€β”€ system_optimizations.sh # Kernel sysctl tuning, memory purging, SSD tweaks
β”‚ β”œβ”€β”€ network_optimizations.sh# Network stack parameters, DNS flushing, firewall
β”‚ β”œβ”€β”€ storage_optimizations.sh# Cache cleanup, font caches, DS_Store removal
β”‚ β”œβ”€β”€ performance_tweaks.sh # Spotlight, Dashboard version-check, animations, Dock
β”‚ β”œβ”€β”€ maintenance.sh # APFS volume verification, periodic scripts, log truncation
β”‚ β”œβ”€β”€ system_monitoring.sh # CPU, Memory, GPU, Battery, Disk & Temperature stats
β”‚ └── power_management.sh # Low power mode toggle, AutoBoot (Intel), MDM detection
└── README.md
```

## 🀝 Contributing
---

We welcome contributions! Here's how you can help:
## πŸ› οΈ Optimizations Summary

1. Fork the repository at https://github.com/koding88/MacBook-Optimization-Script/fork
2. Create your feature branch:
```
git checkout -b feature/AmazingFeature
```
3. Commit your changes:
```
git commit -m 'Add some AmazingFeature'
```
4. Push to the branch:
```
git push origin feature/AmazingFeature
```
5. Open a Pull Request at https://github.com/koding88/MacBook-Optimization-Script/pulls
| Module | Feature | Description |
| :--- | :--- | :--- |
| **System** | Kernel Sysctl Tuning | Optimizes `maxvnodes`, `maxproc`, `maxfiles`, and IPC socket limits. |
| **Memory** | RAM Purge & Cache Flush | Purges inactive RAM pages and flushes disk buffers via `sync`. |
| **Storage** | Cache & `.DS_Store` Cleanup | Safely clears user/system caches and cleans hidden `.DS_Store` files. |
| **Network** | TCP & DNS Tuning | Sets `delayed_ack=0`, blackhole routing, and flushes `mDNSResponder`. |
| **Performance** | Animations & Dock | Speeds up window resizing, launch animations, and Dock hide/show delays. |
| **Maintenance** | APFS Volume Check | Modern `diskutil verifyVolume` replacement for legacy permission checks. |
| **Power** | Low Power & AutoBoot | Toggles Low Power Mode and manages lid auto-start (Intel Macs). |
| **Rollback** | Revert to Backup / Defaults | Restores native user preferences from backup file or macOS defaults. |

For more details, please see our [Contributing Guidelines](CONTRIBUTING.md).
---

## πŸ”’ Security
## πŸ”’ Security & System Requirements

This script requires administrative privileges. Please:
- **Supported OS:** macOS 10.15 (Catalina) through macOS 15+ (Sequoia).
- **Privileges:** Standard user with `sudo` administrative rights when applying system tweaks.
- **Safety:** Non-destructive; protected system files are preserved on SSV-enabled releases.

- Review the code before running
- Keep your system up to date
- Back up important data
- Report security issues through our [Security Policy](SECURITY.md)
---

## πŸ“ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## πŸ™ Acknowledgments

- [Apple Developer Documentation](https://developer.apple.com/documentation/)
- [MacOS Command Line Tools](https://developer.apple.com/library/archive/technotes/tn2002/tn2002.html)
- All [contributors](https://github.com/koding88/MacBook-Optimization-Script/graphs/contributors)

## πŸ“ž Support

Need help? Here are some resources:

- πŸ› Report bugs in [Issues](https://github.com/koding88/MacBook-Optimization-Script/issues)
- πŸ“§ Contact: [duongngocanh2k03@gmail.com](mailto:duongngocanh2k03@gmail.com)

---
Distributed under the MIT License. See `LICENSE` for details.
Loading