#!/bin/bash

################################################################################
# Example: Plex Backup with Simplified Metrics
################################################################################
#
# This is an example showing how to integrate the simplified metrics system
# into the existing Plex backup script for basic status tracking.
#
# The modifications show the minimal changes needed to add metrics tracking
# to any backup script.
#
################################################################################

# Load the simplified metrics library
source "$(dirname "$0")/../lib/unified-backup-metrics.sh"

# Original backup script variables
SERVICE_NAME="plex"
BACKUP_ROOT="/mnt/share/media/backups/plex"
PLEX_DATA_DIR="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server"

# Plex files to backup
declare -A PLEX_FILES=(
    ["database"]="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db"
    ["blobs"]="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.blobs.db"
    ["preferences"]="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Preferences.xml"
)

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_message() {
    echo -e "${BLUE}[$(date '+%H:%M:%S')]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[$(date '+%H:%M:%S')] SUCCESS:${NC} $1"
}

log_error() {
    echo -e "${RED}[$(date '+%H:%M:%S')] ERROR:${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[$(date '+%H:%M:%S')] WARNING:${NC} $1"
}

# Modified backup function with simplified metrics integration
backup_plex_with_json() {
    log_message "Starting Plex backup with simplified metrics..."
    
    # Initialize metrics tracking
    if ! metrics_backup_start "$SERVICE_NAME" "Plex Media Server backup" "$BACKUP_ROOT"; then
        log_error "Failed to initialize metrics tracking"
        return 1
    fi
    
    log_message "Metrics tracking initialized for service: $SERVICE_NAME"
    
    # Phase 1: Stop Plex service
    log_message "Stopping Plex Media Server..."
    metrics_update_status "stopping_service" "Stopping Plex Media Server"
    
    if sudo systemctl stop plexmediaserver.service; then
        log_success "Plex service stopped"
        sleep 3
    else
        log_error "Failed to stop Plex service"
        metrics_backup_complete "failed" "Failed to stop Plex service"
        return 1
    fi
    
    # Phase 2: Backup files
    log_message "Starting file backup phase..."
    metrics_update_status "backing_up_files" "Backing up Plex database files"
    
    local backup_errors=0
    local files_backed_up=0
    
    # Ensure backup directory exists
    mkdir -p "$BACKUP_ROOT"
    
    # Backup each Plex file
    for nickname in "${!PLEX_FILES[@]}"; do
        local source_file="${PLEX_FILES[$nickname]}"
        local filename=$(basename "$source_file")
        local backup_file="$BACKUP_ROOT/$filename"
        
        log_message "Backing up: $filename"
        
        if [ -f "$source_file" ]; then
            # Copy file
            if cp "$source_file" "$backup_file"; then
                # Get file information
                local file_size=$(stat -c%s "$backup_file" 2>/dev/null || echo "0")
                
                # Verify backup
                if [ -f "$backup_file" ] && [ "$file_size" -gt 0 ]; then
                    log_success "Successfully backed up: $filename"
                    metrics_file_backup_complete "$source_file" "$file_size" "success"
                    files_backed_up=$((files_backed_up + 1))
                else
                    log_error "Backup verification failed: $filename"
                    metrics_file_backup_complete "$source_file" "0" "failed"
                    backup_errors=$((backup_errors + 1))
                fi
            else
                log_error "Failed to copy: $filename"
                metrics_file_backup_complete "$source_file" "0" "failed"
                backup_errors=$((backup_errors + 1))
            fi
        else
            log_warning "Source file not found: $source_file"
            metrics_file_backup_complete "$source_file" "0" "skipped"
        fi
    done
    
    json_backup_time_phase "backup" "$phase_start"
    
    # Phase 3: Create archive (if files were backed up)
    if [ "$files_backed_up" -gt 0 ]; then
        log_message "Creating compressed archive..."
        metrics_update_status "creating_archive" "Creating compressed archive"
        
        local archive_name="plex-backup-$(date +%Y%m%d_%H%M%S).tar.gz"
        local archive_path="$BACKUP_ROOT/$archive_name"
        
        # Create archive from backed up files
        if tar -czf "$archive_path" -C "$BACKUP_ROOT" \
            $(find "$BACKUP_ROOT" -maxdepth 1 -name "*.db" -o -name "*.xml" -exec basename {} \;); then
            
            local archive_size=$(stat -c%s "$archive_path" 2>/dev/null || echo "0")
            
            log_success "Created archive: $archive_name"
            metrics_file_backup_complete "$archive_path" "$archive_size" "success"
            
            # Cleanup individual backup files
            find "$BACKUP_ROOT" -maxdepth 1 -name "*.db" -o -name "*.xml" | xargs rm -f
            
        else
            log_error "Failed to create archive"
            backup_errors=$((backup_errors + 1))
        fi
    fi
    
    # Phase 4: Restart Plex service
    log_message "Restarting Plex Media Server..."
    metrics_update_status "starting_service" "Restarting Plex Media Server"
    
    if sudo systemctl start plexmediaserver.service; then
        log_success "Plex service restarted"
        sleep 3
    else
        log_warning "Failed to restart Plex service"
    fi
    
    # Complete backup session
    local final_status="success"
    local completion_message="Backup completed successfully"
    
    if [ "$backup_errors" -gt 0 ]; then
        final_status="partial"
        completion_message="Backup completed with $backup_errors errors"
    fi
    
    if [ "$files_backed_up" -eq 0 ]; then
        final_status="failed"
        completion_message="No files were successfully backed up"
    fi
    
    metrics_backup_complete "$final_status" "$completion_message"
    
    # Final summary
    log_message "Backup Summary:"
    log_message "  Files backed up: $files_backed_up"
    log_message "  Errors: $backup_errors"
    log_message "  Status: $final_status"
    log_message "  Metrics tracking: Simplified JSON status file"
    
    return $backup_errors
}

# Example of checking current status
show_current_status() {
    echo "Current backup status:"
    if metrics_get_status "$SERVICE_NAME"; then
        echo "Status retrieved successfully"
    else
        echo "No status available for service: $SERVICE_NAME"
    fi
}

# Main execution
main() {
    case "${1:-backup}" in
        "backup")
            backup_plex_with_json
            ;;
        "status")
            show_current_status
            ;;
        "help")
            echo "Usage: $0 [backup|status|help]"
            echo ""
            echo "  backup  - Run backup with simplified metrics tracking"
            echo "  status  - Show current backup status"
            echo "  help    - Show this help message"
            ;;
        *)
            echo "Unknown command: $1"
            echo "Use 'help' for usage information"
            exit 1
            ;;
    esac
}

# Run main function
main "$@"
