# Plex Database Repair Utility

## Overview

The `plex-database-repair.sh` script provides comprehensive database repair functionality for Plex Media Server. It has been extracted from the `backup-plex.sh` script to be reusable across multiple scripts in the Plex management suite.

## Features

- **Database Integrity Verification**: Uses Plex's custom SQLite binary for accurate integrity checking
- **WAL File Management**: Properly handles Write-Ahead Logging files during repair operations
- **Multiple Repair Strategies**: 
  1. SQL Dump/Restore approach with validation
  2. Schema recreation with data recovery
  3. Recovery from previous backups
- **Comprehensive Error Handling**: Graceful recovery and rollback on failure
- **Ownership Preservation**: Ensures proper file ownership for the plex user

## Usage

### Command Line Interface

```bash
# Check database integrity only
./plex-database-repair.sh check <database_file>

# Attempt to repair corrupted database
./plex-database-repair.sh repair <database_file>

# Force repair without prompts (for automation)
./plex-database-repair.sh force-repair <database_file>
```

### Integration with Other Scripts

The repair script is designed to be called from other scripts:

```bash
# Source the script to use its functions
source /path/to/plex-database-repair.sh

# Use functions directly
check_database_integrity "/path/to/database.db"
repair_database "/path/to/database.db" false
```

## Examples

### Basic Integrity Check

```bash
./plex-database-repair.sh check "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db"
```

### Repair Corrupted Database

```bash
./plex-database-repair.sh repair "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db"
```

## Exit Codes

- **0**: Success (database is healthy or successfully repaired)
- **1**: Database has issues but repair failed
- **2**: Critical error (cannot access database or repair tools)

## Dependencies

- **Plex Media Server**: Must be installed with the custom SQLite binary
- **Standard Unix tools**: `cp`, `mv`, `rm`, `chown`, `sync`
- **sudo access**: Required for accessing Plex files and changing ownership

## Integration Points

### plex.sh

The main Plex management script uses this repair utility for:
- Pre-startup integrity checking
- Manual database repair command (`plex.sh repair`)

### backup-plex.sh

The backup script uses this utility for:
- Pre-backup integrity verification
- Automatic repair during backup process
- Database corruption detection and handling

## Technical Details

### Repair Strategies

1. **SQL Dump/Restore**:
   - Creates a complete SQL dump of the corrupted database
   - Validates dump contains essential Plex tables
   - Creates new database from validated dump
   - Verifies integrity of repaired database

2. **Schema Recreation**:
   - Extracts schema from corrupted database
   - Creates new database with clean schema
   - Attempts table-by-table data recovery
   - Considers successful if 80% of tables recovered

3. **Backup Recovery**:
   - Locates most recent valid backup
   - Extracts and validates backup database
   - Replaces corrupted database with backup version

### WAL File Handling

The script properly manages SQLite Write-Ahead Logging files:

- **Prepare**: Performs WAL checkpoint and creates backups
- **Cleanup**: Removes WAL/SHM files and restores WAL mode
- **Restore**: Restores WAL/SHM files if repair fails

### Safety Measures

- Creates pre-repair backups before any modifications
- Uses atomic file operations where possible
- Forces filesystem sync after critical operations
- Preserves original database if all repair strategies fail
- Ensures proper file ownership and permissions

## Troubleshooting

### Common Issues

1. **Permission Denied**: Ensure script has sudo access and Plex files are accessible
2. **Plex SQLite Not Found**: Verify Plex Media Server is properly installed
3. **Insufficient Disk Space**: Repair process requires significant temporary space
4. **Service Access**: Ensure Plex service can be stopped/started during repair

### Recovery Options

If repair fails:
1. Check `backup-plex.sh` for recent backups
2. Examine corrupted database directories for recovery files
3. Consider manual database reconstruction using Plex tools
4. Contact Plex support for advanced recovery options

## Related Scripts

- **plex.sh**: Main Plex service management
- **backup-plex.sh**: Comprehensive backup solution
- **restore-plex.sh**: Backup restoration utilities
- **validate-plex-backups.sh**: Backup validation tools

## Changelog

### v1.0 (2025-06-18)
- Initial extraction from backup-plex.sh
- Added standalone command-line interface
- Enhanced ownership preservation
- Improved error handling and logging
