# Plex Management Script Documentation

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

This document provides comprehensive documentation for the modern `plex.sh` script, featuring enhanced service management with progress indicators, dependency validation, safety checks, and comprehensive error handling.

## Script Overview

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

The enhanced `plex.sh` script is a modern Plex service management tool that performs the following advanced tasks:

1. **Smart Service Management**: Intelligent start/stop/restart operations with dependency checking
2. **Library Scanner Integration**: Integrated access to comprehensive library scanning operations
3. **Enhanced Status Display**: Detailed service status with health indicators and port monitoring
4. **Safety Validation**: Pre-operation checks and post-operation verification
5. **Progress Indicators**: Visual feedback for all operations with timing information
6. **Comprehensive Logging**: Detailed logging with color-coded output and timestamps
7. **Configuration Validation**: Checks for common configuration issues
8. **Network Monitoring**: Port availability and network configuration validation
9. **Process Management**: Advanced process monitoring and cleanup capabilities
10. **Recovery Operations**: Automatic recovery from common service issues
11. **Performance Monitoring**: Service health and resource usage tracking

## Related Scripts in the Plex Ecosystem

This script is part of a comprehensive Plex management suite:

### Core Management Scripts

- **`plex.sh`** (this script) - Service management and control
- **`scan-plex-libraries.sh`** ⭐ **NEW** - Comprehensive library scanning and metadata management
- **`backup-plex.sh`** - Database backup with integrity checking and auto-repair
- **`restore-plex.sh`** - Safe database restoration with validation

### Recovery and Maintenance Scripts

- **`recover-plex-database.sh`** - Advanced database recovery operations
- **`icu-aware-recovery.sh`** - ICU-aware database recovery for Unicode issues
- **`nuclear-plex-recovery.sh`** - Last-resort database replacement and recovery
- **`validate-plex-recovery.sh`** - Recovery operation validation and verification

### Monitoring and Testing Scripts

- **`monitor-plex-backup.sh`** - Real-time backup monitoring dashboard
- **`validate-plex-backups.sh`** - Backup validation and health monitoring
- **`test-plex-backup.sh`** - Comprehensive backup testing suite
- **`integration-test-plex.sh`** - End-to-end integration testing

### Utility Scripts

- **`plex-recent-additions.sh`** - Recent media additions reporting and statistics

## Library Scanner Integration ⭐ **NEW**

### Overview

The `plex.sh` script now includes integrated access to comprehensive library scanning functionality through the new `scan-plex-libraries.sh` script. This integration provides seamless access to all Plex Media Scanner operations directly from the main management interface.

### Library Scanner Features

The integrated library scanner provides:

- **Library Management**: List all Plex library sections with IDs and names
- **Media Scanning**: Scan for new media files (individual libraries or all at once)
- **Metadata Refresh**: Refresh library metadata with force options for complete rebuilds
- **Deep Analysis**: Comprehensive media analysis for codec information and metadata
- **Thumbnail Generation**: Generate preview thumbnails and fanart images
- **Library Structure**: Display hierarchical library structure and organization
- **Interactive Mode**: User-friendly menu system for easy library management
- **Batch Operations**: Perform operations on all libraries or specific selections
- **Error Handling**: Comprehensive validation and error reporting
- **Service Integration**: Automatic Plex service status validation before operations

### Scanner Integration Commands

The library scanner is accessible through the main `plex.sh` script:

```bash
# Launch interactive scanner interface
./plex.sh scan

# Pass commands directly to scanner
./plex.sh scan list                    # List all libraries
./plex.sh scan scan                    # Scan all libraries for new media
./plex.sh scan scan 29                 # Scan specific library (ID 29)
./plex.sh scan refresh 29 true         # Force refresh specific library
./plex.sh scan analyze 29 true         # Deep analyze specific library
./plex.sh scan generate 29             # Generate thumbnails for library
./plex.sh scan tree 29                 # Show library structure
```

### Direct Scanner Access

The scanner can also be accessed directly:

```bash
# Direct script execution
./scan-plex-libraries.sh interactive   # Interactive mode
./scan-plex-libraries.sh list          # List libraries
./scan-plex-libraries.sh scan          # Scan all libraries
./scan-plex-libraries.sh -v scan 29    # Verbose scan of specific library

# Via aliases (if shell configuration is loaded)
plex-scan                               # Launch via plex.sh integration
plex-scanner list                       # Direct scanner access
plex-scanner scan 29                    # Direct scan of specific library
```

### Scanner Command Reference

#### Core Scanner Commands

- **`list`** - Display all available library sections with IDs and names
- **`scan [section_id]`** - Scan for new media files (all libraries if no ID specified)
- **`refresh [section_id] [force]`** - Refresh metadata (set force=true for complete refresh)
- **`analyze [section_id] [deep]`** - Analyze media files (set deep=true for comprehensive analysis)
- **`generate [section_id]`** - Generate thumbnails and fanart images
- **`tree <section_id>`** - Display hierarchical library structure (requires section ID)
- **`interactive`** - Launch interactive menu system

#### Scanner Options

- **`-v, --verbose`** - Enable verbose output for detailed operation information
- **`-h, --help`** - Display comprehensive help and usage information

#### Example Scanner Operations

```bash
# List all available libraries with their section IDs
$ ./plex.sh scan list
Available Library Sections:
=========================
  29: Movies
  30: TV Shows
  31: Music

# Scan Movies library for new content
$ ./plex.sh scan scan 29
[>] Scanning library section 29 for new media...
[✓] Library section 29 scan completed

# Force refresh all libraries (complete metadata rebuild)
$ ./plex.sh scan refresh "" true
[~] Refreshing metadata for all libraries...
[i] Refreshing section 29...
[✓] Section 29 refreshed successfully
[i] Refreshing section 30...
[✓] Section 30 refreshed successfully
[✓] All libraries refreshed successfully

# Deep analyze TV Shows library
$ ./plex.sh scan analyze 30 true
[?] Analyzing media in library section 30...
[✓] Library section 30 analysis completed

# Generate thumbnails for Movies library
$ ./plex.sh scan generate 29
[*] Generating thumbnails for library section 29...
[✓] Thumbnails generated for library section 29
```

### Interactive Scanner Mode

The interactive mode provides a user-friendly menu system:

```bash
$ ./plex.sh scan
🎬 Plex Library Scanner - Interactive Mode
Select an operation to perform:

Available Operations:
1) List all libraries
2) Scan libraries for new media
3) Refresh library metadata
4) Analyze library media
5) Generate thumbnails
6) Show library tree
q) Quit

Choose an option [1-6,q]: 2

Scan Options:
1) Scan all libraries
2) Scan specific library
Choose [1-2]: 1

[>] Scanning all libraries for new media...
[✓] All libraries scanned successfully
```

### Scanner Error Handling and Validation

The library scanner includes comprehensive error handling:

- **Service Validation**: Automatically checks if Plex Media Server is running
- **Scanner Detection**: Locates Plex Media Scanner binary across different installation paths
- **Section ID Validation**: Verifies library section IDs exist before operations
- **Operation Verification**: Confirms successful completion of all scanner operations
- **Graceful Failure**: Provides helpful error messages and recovery suggestions

### Scanner Logging and Monitoring

All scanner operations are logged:

- **Operation Logs**: Detailed logs written to `/home/acedanger/shell/logs/plex-scanner.log`
- **Timestamp Tracking**: All operations include precise timestamps
- **Verbose Mode**: Enhanced debugging information available with `-v` flag
- **Status Reporting**: Real-time status updates during long-running operations

### Scanner Performance Considerations

For optimal performance:

- **Large Libraries**: Scanner operations may take considerable time for large media collections
- **Deep Analysis**: Deep analysis is resource-intensive, use selectively
- **Concurrent Operations**: Avoid running multiple scanner operations simultaneously
- **System Resources**: Scanner operations can be CPU and I/O intensive during execution

### Scanner Best Practices

Recommended usage patterns:

1. **Regular Scanning**: Set up regular scans for libraries with frequent media additions
2. **Selective Operations**: Use specific section IDs for targeted operations when possible
3. **Monitor Progress**: Use verbose mode to understand operation progress and impact
4. **Service Health**: Ensure Plex service is healthy before performing scanner operations
5. **Batch Operations**: For multiple libraries, consider using "scan all" for efficiency

### Scanner Troubleshooting

Common issues and solutions:

1. **"Plex Media Server is not running"**
   - Start Plex: `./plex.sh start`
   - Verify status: `./plex.sh status`

2. **"Plex Media Scanner binary not found"**
   - Verify Plex installation is complete
   - Check if binary exists in standard locations
   - Ensure proper system PATH configuration

3. **"Section ID not found"**
   - Use `./plex.sh scan list` to see valid section IDs
   - Verify the library hasn't been deleted or renamed

4. **Scanner operations timeout or fail**
   - Check system resources (CPU, memory, disk I/O)
   - Verify media files are accessible and not corrupted
   - Review scanner logs for detailed error information

### Scanner Bash Completion ⭐ **NEW**

The library scanner includes comprehensive bash completion support:

#### Tab Completion Features

- **Command Completion**: Tab completion for all scanner commands and options
- **Context-Aware**: Different completions based on command context
- **Boolean Flags**: Smart completion for `true`/`false` values where applicable
- **Alias Support**: Completion works with all plex-related aliases

#### Example Tab Completion Usage

```bash
# Main plex.sh command completion
$ ./plex.sh <TAB>
start  stop  restart  status  scan  repair  nuclear  help

# Scanner sub-command completion
$ ./plex.sh scan <TAB>
list  scan  refresh  analyze  generate  tree  interactive  -v  --verbose  -h  --help

# Boolean flag completion for refresh and analyze
$ ./plex.sh scan refresh 29 <TAB>
true  false

$ ./plex.sh scan analyze 29 <TAB>
true  false

# Direct scanner completion
$ ./scan-plex-libraries.sh <TAB>
list  scan  refresh  analyze  generate  tree  interactive

# Alias completion
$ plex-scan <TAB>
list  scan  refresh  analyze  generate  tree  interactive

$ plex-scanner <TAB>
list  scan  refresh  analyze  generate  tree  interactive
```

#### Completion Installation

Bash completion is automatically installed by the setup scripts:

- **Automatic Setup**: Installed by `bootstrap.sh` and `setup.sh`
- **Shell Integration**: Sourced in `.zshrc` for immediate availability
- **Alias Support**: Works with all plex-related aliases (`plex`, `plex-scan`, `plex-scanner`, etc.)

#### Manual Completion Setup

If needed, completion can be enabled manually:

```bash
# Enable bash completion in zsh
autoload -U +X bashcompinit && bashcompinit
autoload -U compinit && compinit -u

# Source the completion script
source /home/acedanger/shell/completions/plex-scripts-completion.bash
```

## Enhanced Features

### Smart Terminal Detection and Color Output

The script includes intelligent terminal detection and color management:

- **Automatic Color Detection**: Detects terminal capabilities and adjusts output accordingly
- **Environment Variable Support**: Respects `NO_COLOR` environment variable for accessibility
- **Porcelain Mode**: `--porcelain` or `-p` provides machine-readable output for automation
- **ANSI Escape Handling**: Properly handles color codes when called from other scripts

### System Integration and Automation

- **update.sh Integration**: Automatically called during system updates with simple output mode
- **Non-Interactive Operation**: Designed to work seamlessly when called from other scripts
- **Service Presence Detection**: Gracefully handles systems without Plex installed
- **Root User Prevention**: Explicitly prevents running as root for security

### Environment Variables

The script supports several environment variables for customization:

```bash
# Disable color output entirely
NO_COLOR=1 ./plex.sh status

# Force porcelain mode for machine-readable output
./plex.sh --porcelain start

# Check terminal capabilities
TERM=dumb ./plex.sh status  # Forces simple output
```

### Smart Service Management

The enhanced script includes intelligent service operations:

- **Dependency Validation**: Checks for required services and dependencies before operations
- **Safe Stop Operations**: Graceful shutdown with proper wait times and verification
- **Intelligent Restart**: Combines stop and start operations with validation between steps
- **Service Health Checks**: Comprehensive status validation beyond simple systemctl status

### Progress Indicators and User Experience

- **Visual Progress**: Real-time progress indicators for all operations
- **Timing Information**: Displays operation duration and timestamps
- **Color-coded Output**: Success (green), error (red), warning (yellow), info (blue)
- **Clear Status Messages**: Descriptive messages for all operations and their outcomes

### Advanced Status Display

The `status` command provides comprehensive information:

```bash
./plex.sh status
```

Shows:

- Service status and health
- Process information and resource usage
- Network port availability (32400/tcp)
- Configuration file validation
- Recent log entries and error conditions
- Performance metrics and uptime information

### Safety and Validation Features

- **Pre-operation Checks**: Validates system state before making changes
- **Post-operation Verification**: Confirms operations completed successfully
- **Configuration Validation**: Checks for common configuration issues
- **Network Validation**: Verifies port availability and network configuration
- **Recovery Capabilities**: Automatic recovery from common service issues

## Command Line Usage

### Basic Operations

```bash
# Start Plex Media Server
./plex.sh start

# Stop Plex Media Server
./plex.sh stop

# Restart Plex Media Server
./plex.sh restart

# Display comprehensive status
./plex.sh status

# Launch library scanner
./plex.sh scan
```

### Available Commands

The script supports the following commands:

```bash
# Basic service operations
./plex.sh start      # Start Plex Media Server
./plex.sh stop       # Stop Plex Media Server
./plex.sh restart    # Restart Plex Media Server (also accepts 'reload')
./plex.sh status     # Show detailed service status (also accepts 'info')
./plex.sh scan       # Launch library scanner (NEW)
./plex.sh logs       # Display recent Plex Media Server logs
./plex.sh help       # Show help message (also accepts '--help' or '-h')

# Library scanner operations (NEW)
./plex.sh scan                          # Interactive scanner mode
./plex.sh scan list                     # List all library sections
./plex.sh scan scan                     # Scan all libraries for new media
./plex.sh scan scan 29                  # Scan specific library (ID 29)
./plex.sh scan refresh 29 true          # Force refresh specific library
./plex.sh scan analyze 29 true          # Deep analyze specific library
./plex.sh scan generate 29              # Generate thumbnails for library
./plex.sh scan tree 29                  # Show library structure

# Logs command with options
./plex.sh logs       # Display last 20 lines of Plex logs
./plex.sh logs -n 50 # Display last 50 lines of Plex logs
./plex.sh logs -f    # Follow logs in real-time
./plex.sh logs --follow --lines 100  # Follow logs with custom line count

# Porcelain mode for machine-readable output
./plex.sh --porcelain start          # Machine-readable service output
./plex.sh --porcelain status         # Machine-readable status output

# Environment variable examples
NO_COLOR=1 ./plex.sh status                    # Disable colors
./plex.sh --porcelain start                    # Machine-readable output
```

**Note**: The script automatically detects when it's being called from other scripts (like `update.sh`) and adjusts its output accordingly.

### Integration with Other Scripts

The `plex.sh` script is designed to work seamlessly with other Plex management scripts and system automation:

```bash
# Used by update.sh during system updates (automatic porcelain output)
./update.sh  # Automatically calls plex.sh --porcelain stop/start

# Used by backup script for safe service management
./backup-plex.sh  # Automatically calls plex.sh stop/start

# Used by recovery scripts for service control
./recover-plex-database.sh  # Uses plex.sh for service management

# Library scanner integration with service management
./plex.sh scan scan           # Scan all libraries
./plex.sh scan refresh "" true  # Force refresh all libraries after service restart

# Manual integration with porcelain output
./plex.sh --porcelain start  # For use in scripts/automation

# Scanner integration in maintenance scripts
./plex.sh scan scan           # Regular media scanning
./plex.sh scan analyze        # Weekly deep analysis
./plex.sh scan generate       # Thumbnail regeneration
```

### Security and Safety Features

- **Root Prevention**: Script refuses to run as root user for security
- **Safe Defaults**: Uses conservative settings for service operations
- **Error Handling**: Comprehensive error checking and reporting
- **Graceful Degradation**: Works on systems without Plex installed

## Detailed Operation Steps

### Start Operation Process

1. **Pre-start Validation**
   - Check if service is already running
   - Validate system dependencies
   - Check port availability (32400/tcp)
   - Verify configuration files

2. **Service Start**
   - Execute systemctl start command
   - Monitor startup progress
   - Display progress indicators

3. **Post-start Verification**
   - Confirm service is active
   - Verify network port is accessible
   - Check process health
   - Display success confirmation

### Stop Operation Process

1. **Pre-stop Checks**
   - Verify service is currently running
   - Check for active connections
   - Prepare for graceful shutdown

2. **Graceful Shutdown**
   - Send stop signal to service
   - Allow proper shutdown time
   - Monitor shutdown progress

3. **Verification and Cleanup**
   - Confirm service has stopped
   - Verify process termination
   - Clean up any remaining resources

### Status Operation Details

The status command provides comprehensive system information:

- **Service Status**: Active/inactive state and health
- **Process Information**: PID, memory usage, CPU utilization
- **Network Status**: Port availability and connection status
- **Configuration**: Validation of key configuration files
- **Recent Activity**: Latest log entries and system events
- **Performance Metrics**: Uptime, resource usage, response times

### Logs Operation Details

The logs command provides flexible log viewing capabilities:

```bash
# Basic log viewing (last 20 lines)
./plex.sh logs

# Custom line count
./plex.sh logs -n 50
./plex.sh logs --lines 100

# Real-time log following
./plex.sh logs -f
./plex.sh logs --follow

# Combined options
./plex.sh logs --follow --lines 50
```

**Logs Command Features:**

- **Flexible Line Count**: Specify number of log lines to display (default: 20)
- **Real-time Following**: Use `-f` or `--follow` to tail logs in real-time
- **Systemd Integration**: Uses `journalctl` for reliable log access
- **Porcelain Mode Support**: Works with `--porcelain` for script automation
- **Error Handling**: Graceful handling when service is not available

**Logs Command Options:**

- `-n, --lines NUMBER`: Number of log lines to display (default: 20)
- `-f, --follow`: Follow logs in real-time (like `tail -f`)
- Can be combined with global `--porcelain` option for clean output

## Configuration and Dependencies

### Environment Variable Configuration

The script respects several environment variables for customization:

- **`NO_COLOR`**: Set to `1` to disable all color output (accessibility compliance)
- **`--porcelain`**: Command-line option to force machine-readable output (for automation)
- **`TERM`**: Automatically detected; `dumb` terminals get simple output

### System Requirements

- **Operating System**: systemd-based Linux distribution
- **Permissions**: sudo access for systemctl operations (script prevents running as root)
- **Network**: Port 32400/tcp available for Plex communications
- **Dependencies**: systemctl, basic shell utilities
- **Service**: plexmediaserver.service (gracefully handles absence)

### Configuration Validation

The script validates key configuration elements:

- **Service Definition**: Ensures plexmediaserver.service is properly configured
- **Network Configuration**: Validates port availability and network bindings
- **File Permissions**: Checks critical file and directory permissions
- **Process Limits**: Verifies system resource limits are appropriate

### Integration Points

The script integrates with the broader Plex management ecosystem:

- **Backup Operations**: Called by `backup-plex.sh` for safe service management
- **Recovery Procedures**: Used by recovery scripts for controlled service restart
- **Testing Framework**: Utilized by integration tests for service validation
- **Monitoring Systems**: Provides status information for monitoring dashboards

### System Update Integration

The script is designed to work seamlessly with system update processes:

- **Automatic Integration**: Called by `update.sh` during system updates
- **Service Management**: Safely stops Plex before package updates, restarts after completion
- **Porcelain Mode**: Uses `--porcelain` for clean, log-friendly output
- **Graceful Handling**: Properly handles systems without Plex installed
- **Error Prevention**: Prevents interruption of package manager operations

Example system update integration:

```bash
# In update.sh - automatically stops Plex before updates
/home/acedanger/shell/plex/plex.sh --porcelain stop

# Package updates occur here...

# In update.sh - automatically starts Plex after updates
/home/acedanger/shell/plex/plex.sh --porcelain start
```

This integration ensures that Plex databases and processes don't interfere with system package updates while maintaining service availability.

## Error Handling and Troubleshooting

### Common Issues and Solutions

1. **Service Won't Start**
   - Check configuration files for syntax errors
   - Verify port 32400 is not in use by another process
   - Confirm Plex user has necessary permissions
   - Review system logs for specific error messages

2. **Service Won't Stop**
   - Check for active media streaming sessions
   - Verify no stuck processes are preventing shutdown
   - Use `--force` option for forced termination if necessary
   - Review process tree for dependent processes

3. **Network Issues**
   - Confirm firewall settings allow port 32400
   - Check network interface configuration
   - Verify DNS resolution if using remote access
   - Test local network connectivity

### Debug Mode

Enable verbose logging for troubleshooting:

```bash
# Run with enhanced debugging
./plex.sh status --debug

# Check system integration
./plex.sh start --validate --debug
```

## Security Considerations

### Access Control

- Script requires sudo privileges for systemctl operations
- Service runs under dedicated plex user account
- Network access restricted to required ports only
- Configuration files protected with appropriate permissions

### Best Practices

- Regularly update Plex Media Server software
- Monitor service logs for security events
- Restrict network access to trusted networks
- Use strong authentication for remote access
- Regularly backup configuration and databases

## Performance Optimization

### Service Tuning

The script supports performance optimization through:

- **Process Priority**: Adjusts service priority for optimal performance
- **Resource Limits**: Configures appropriate memory and CPU limits
- **Network Tuning**: Optimizes network buffer sizes and timeouts
- **Disk I/O**: Configures efficient disk access patterns

### Monitoring Integration

Integrates with monitoring systems:

- **Prometheus Metrics**: Exports service metrics for monitoring
- **Log Aggregation**: Structured logging for centralized analysis
- **Health Checks**: Regular health validation for proactive monitoring
- **Performance Tracking**: Resource usage tracking and alerting

## Automation and Scheduling

### Systemd Integration

The script works seamlessly with systemd:

```bash
# Enable automatic startup
sudo systemctl enable plexmediaserver

# Check service dependencies
systemctl list-dependencies plexmediaserver
```

### Cron Integration

For scheduled operations:

```bash
# Weekly service restart for maintenance
0 3 * * 0 /home/acedanger/shell/plex/plex.sh restart --safe

# Daily health check
0 6 * * * /home/acedanger/shell/plex/plex.sh status --validate

# Automated library scanning (NEW)
0 4 * * * /home/acedanger/shell/plex/plex.sh scan scan          # Daily scan for new media
0 2 * * 0 /home/acedanger/shell/plex/plex.sh scan refresh "" true  # Weekly metadata refresh
0 1 * * 1 /home/acedanger/shell/plex/plex.sh scan analyze       # Weekly media analysis
```

## Exit Codes and Return Values

The script uses standard exit codes for automation:

- **0**: Operation completed successfully
- **1**: General error or operation failed
- **2**: Invalid command line arguments
- **3**: Service operation timeout
- **4**: Permission denied or insufficient privileges
- **5**: Network or connectivity issues
- **6**: Configuration validation failed
- **7**: Dependency check failed

These exit codes enable reliable automation and error handling in larger scripts and systems.

## Important Information

### Prerequisites

- Ensure that the script is executable:

  ```bash
  chmod +x plex.sh
  ```

- The script uses `systemctl` to manage the Plex Media Server service. Ensure that `systemctl` is available on your system.
- The script requires `sudo` privileges to manage the Plex Media Server service. Ensure that you have the necessary permissions.

### Script Integration

This script is designed to work as part of the broader Plex management ecosystem:

- **Backup Integration**: Automatically called by backup scripts for safe service management
- **Recovery Integration**: Used by recovery scripts for controlled service operations
- **Testing Integration**: Utilized by testing frameworks for service validation
- **Monitoring Integration**: Provides status information for monitoring systems

### Compatibility

- **Operating Systems**: Tested on Ubuntu 20.04+, Debian 10+, CentOS 8+
- **Plex Versions**: Compatible with Plex Media Server 1.25.0 and later
- **Dependencies**: Minimal external dependencies for maximum compatibility
- **Architecture**: Supports both x86_64 and ARM64 architectures

By following this documentation, you should be able to effectively use the enhanced `plex.sh` script as part of your comprehensive Plex media server management strategy.
