# Plex Backup and Management Scripts

**Author:** Peter Wood <peter@peterwood.dev>

This directory contains a comprehensive suite of scripts for Plex Media Server backup, restoration, validation, recovery, and management operations. The system provides enterprise-grade backup capabilities with automated integrity checking, multiple recovery strategies, and extensive monitoring.

## 🎯 Quick Start

```bash
# Create a backup with automatic integrity checking and repair
./backup-plex.sh

# Monitor backup system health
./monitor-plex-backup.sh --watch

# Validate all existing backups
./validate-plex-backups.sh

# Restore from a specific backup
./restore-plex.sh plex-backup-20250605_143022.tar.gz

# Basic Plex service management
./plex.sh status
```

## 📁 Scripts Overview

### 🔄 Core Backup & Restoration

#### `backup-plex.sh`

### Enhanced Plex backup script with advanced features

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Database integrity checking with automatic repair capabilities
- WAL file handling for SQLite databases
- Performance monitoring with JSON-based logging
- Parallel verification for improved performance
- Multi-channel notifications (console, webhook, email)
- Comprehensive error handling and recovery
- Automated cleanup of old backups

**Usage:**

```bash
./backup-plex.sh                    # Standard backup with auto-repair
./backup-plex.sh --disable-auto-repair  # Backup without auto-repair
./backup-plex.sh --check-integrity  # Integrity check only
./backup-plex.sh --non-interactive  # Automated mode for cron jobs
./backup-plex.sh --webhook=URL      # Custom webhook notifications
```

#### `restore-plex.sh`

### Safe restoration script with validation

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Interactive backup selection from available archives
- Backup validation before restoration
- Dry-run mode for testing restoration process
- Automatic backup of current data before restoration
- Service management (stop/start Plex during restoration)
- File ownership and permission restoration

**Usage:**

```bash
./restore-plex.sh                                        # List available backups
./restore-plex.sh plex-backup-20250605_143022.tar.gz    # Restore specific backup
./restore-plex.sh --dry-run backup-file.tar.gz          # Test restoration process
./restore-plex.sh --list                                # List all available backups
```

### 🔍 Validation & Monitoring

#### `validate-plex-backups.sh`

### Backup validation and health monitoring

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Archive integrity verification (checksum validation)
- Database integrity checking within backups
- Backup completeness validation
- Automated repair suggestions and fixes
- Historical backup analysis
- Performance metrics and reporting

**Usage:**

```bash
./validate-plex-backups.sh           # Validate all backups
./validate-plex-backups.sh --fix     # Validate and fix issues
./validate-plex-backups.sh --report  # Generate detailed report
./validate-plex-backups.sh --latest  # Validate only latest backup
```

#### `monitor-plex-backup.sh`

### Real-time backup system monitoring dashboard

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Real-time backup system health monitoring
- Performance metrics and trending
- Backup schedule and execution tracking
- Disk space monitoring and alerts
- Service status verification
- Watch mode with auto-refresh

**Usage:**

```bash
./monitor-plex-backup.sh           # Single status check
./monitor-plex-backup.sh --watch   # Continuous monitoring
./monitor-plex-backup.sh --help    # Show help information
```

### 🛠️ Database Recovery Scripts

#### `recover-plex-database.sh`

### Advanced database recovery with multiple strategies

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Progressive recovery strategy (gentle to aggressive)
- Multiple repair techniques (VACUUM, dump/restore, rebuild)
- Automatic backup before recovery attempts
- Database integrity verification at each step
- Rollback capability if recovery fails
- Comprehensive logging and reporting

**Usage:**

```bash
./recover-plex-database.sh                 # Interactive recovery
./recover-plex-database.sh --auto          # Automated recovery
./recover-plex-database.sh --dry-run       # Show recovery plan
./recover-plex-database.sh --gentle        # Gentle repair only
```

#### `icu-aware-recovery.sh`

### ICU-aware database recovery for Unicode issues

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- ICU collation sequence detection and repair
- Unicode-aware database reconstruction
- Advanced SQLite recovery techniques
- Plex service management during recovery

**Usage:**

```bash
./icu-aware-recovery.sh                    # Interactive recovery
./icu-aware-recovery.sh --auto             # Automated recovery
./icu-aware-recovery.sh --check-only       # Check ICU status only
```

#### `nuclear-plex-recovery.sh`

### Last-resort complete database replacement

**Author:** Peter Wood <peter@peterwood.dev>

**⚠️ WARNING:** This script completely replaces existing databases!

**Features:**

- Complete database replacement from backups
- Automatic backup of current (corrupted) databases
- Rollback capability if replacement fails
- Verification of restored database integrity

**Usage:**

```bash
./nuclear-plex-recovery.sh                    # Interactive recovery
./nuclear-plex-recovery.sh --auto             # Automated recovery
./nuclear-plex-recovery.sh --dry-run          # Show what would be done
```

#### `validate-plex-recovery.sh`

### Recovery validation and verification

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Database integrity verification
- Service functionality testing
- Library accessibility checks
- Performance validation
- Web interface connectivity testing

**Usage:**

```bash
./validate-plex-recovery.sh                # Full validation suite
./validate-plex-recovery.sh --quick        # Quick validation checks
./validate-plex-recovery.sh --detailed     # Detailed analysis and reporting
```

### 🧪 Testing Framework

#### `test-plex-backup.sh`

### Comprehensive testing suite

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Unit testing for individual backup components
- Integration testing for full backup workflows
- Database integrity test scenarios
- Performance benchmarking
- Error condition simulation and recovery testing

**Usage:**

```bash
./test-plex-backup.sh              # Run full test suite
./test-plex-backup.sh --unit       # Unit tests only
./test-plex-backup.sh --integration # Integration tests only
./test-plex-backup.sh --quick      # Quick smoke tests
```

#### `integration-test-plex.sh`

### End-to-end integration testing

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Full workflow integration testing
- Isolated test environment creation
- Production-safe testing procedures
- Multi-scenario testing (normal, error, edge cases)
- Cross-script compatibility testing

**Usage:**

```bash
./integration-test-plex.sh                  # Full integration test suite
./integration-test-plex.sh --quick          # Quick smoke tests
./integration-test-plex.sh --performance    # Performance benchmarks
```

### 🎮 Management & Utilities

#### `plex.sh`

### Modern Plex service management

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Service start/stop/restart/status operations
- Web interface launcher
- Styled console output with Unicode symbols
- Service health monitoring
- Interactive menu system

**Usage:**

```bash
./plex.sh start     # Start Plex service
./plex.sh stop      # Stop Plex service
./plex.sh restart   # Restart Plex service
./plex.sh status    # Show service status
./plex.sh web       # Open web interface
./plex.sh           # Interactive menu
```

#### `plex-recent-additions.sh`

### Recent media additions reporting

**Author:** Peter Wood <peter@peterwood.dev>

**Features:**

- Recent additions reporting (configurable time range)
- Library section filtering
- Formatted output with headers and columns
- Direct SQLite database querying

**Usage:**

```bash
./plex-recent-additions.sh         # Show additions from last 7 days
./plex-recent-additions.sh 30      # Show additions from last 30 days
```

## 🏗️ System Architecture

### Script Relationships

```mermaid
graph TD
    A[backup-plex.sh] --> B[validate-plex-backups.sh]
    A --> C[monitor-plex-backup.sh]
    B --> D[restore-plex.sh]
    D --> E[validate-plex-recovery.sh]
    F[recover-plex-database.sh] --> E
    G[icu-aware-recovery.sh] --> E
    H[nuclear-plex-recovery.sh] --> E
    I[test-plex-backup.sh] --> A
    J[integration-test-plex.sh] --> A
    K[plex.sh] --> A
    L[plex-recent-additions.sh] --> A
```

### Data Flow

1. **Backup Creation:** `backup-plex.sh` creates validated backups
2. **Monitoring:** `monitor-plex-backup.sh` tracks system health
3. **Validation:** `validate-plex-backups.sh` ensures backup integrity
4. **Recovery:** Multiple recovery scripts handle different failure scenarios
5. **Restoration:** `restore-plex.sh` safely restores from backups
6. **Verification:** `validate-plex-recovery.sh` confirms successful recovery

## 🔧 Configuration

### Environment Setup

All scripts share common configuration patterns:

- **Backup Location:** `/mnt/share/media/backups/plex`
- **Log Location:** `./logs/` (local) and `/mnt/share/media/backups/logs` (shared)
- **Plex Database Path:** `/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/`
- **Service Name:** `plexmediaserver`

### Notification Configuration

Scripts support multiple notification channels:

- **Webhook notifications:** Custom webhook URL support
- **Email notifications:** Via sendmail (if configured)
- **Console output:** Color-coded status messages

### Performance Tuning

- **Parallel verification:** Enabled by default for faster operations
- **Performance monitoring:** JSON-based metrics collection
- **Automatic cleanup:** Configurable retention policies

## 📊 Monitoring & Alerting

### Health Checks

The monitoring system tracks:

- Backup success/failure rates
- Database integrity status
- Service uptime and performance
- Disk space utilization
- Recovery operation success

### Performance Metrics

- Backup duration and size trends
- Database operation performance
- Service start/stop times
- Recovery operation benchmarks

## 🚨 Emergency Procedures

### Database Corruption

1. **First Response:** Run `backup-plex.sh --check-integrity`
2. **Gentle Recovery:** Try `recover-plex-database.sh --gentle`
3. **Advanced Recovery:** Use `icu-aware-recovery.sh` for Unicode issues
4. **Last Resort:** Execute `nuclear-plex-recovery.sh` with known good backup
5. **Validation:** Always run `validate-plex-recovery.sh` after recovery

### Service Issues

1. **Check Status:** `./plex.sh status`
2. **Restart Service:** `./plex.sh restart`
3. **Monitor Logs:** Check system logs and script logs
4. **Validate Database:** Run integrity checks if service fails to start

## 📚 Additional Documentation

- **[Plex Backup System Guide](plex-backup.md)** - Detailed backup system documentation
- **[Plex Management Guide](plex-management.md)** - Service management procedures
- **[Troubleshooting Guide](troubleshooting.md)** - Common issues and solutions

## 🏷️ Version Information

- **Script Suite Version:** 2.0
- **Author:** Peter Wood <peter@peterwood.dev>
- **Last Updated:** June 2025
- **Compatibility:** Ubuntu 20.04+, Debian 11+
- **Plex Version:** Compatible with Plex Media Server 1.25+

## 📞 Support

For issues, questions, or contributions:

- **Author:** Peter Wood
- **Email:** <peter@peterwood.dev>
- **Repository:** Part of comprehensive shell script collection
