# 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. **Enhanced Status Display**: Detailed service status with health indicators and port monitoring
3. **Safety Validation**: Pre-operation checks and post-operation verification
4. **Progress Indicators**: Visual feedback for all operations with timing information
5. **Comprehensive Logging**: Detailed logging with color-coded output and timestamps
6. **Configuration Validation**: Checks for common configuration issues
7. **Network Monitoring**: Port availability and network configuration validation
8. **Process Management**: Advanced process monitoring and cleanup capabilities
9. **Recovery Operations**: Automatic recovery from common service issues
10. **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
- **`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

## 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
```

### 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 logs       # Display recent Plex Media Server logs
./plex.sh help       # Show help message (also accepts '--help' or '-h')

# 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

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

### 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
```

## 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.
