#!/bin/bash

################################################################################
# Plex Built-in Backup Status Checker
################################################################################
#
# Author: Peter Wood <peter@peterwood.dev>
# Description: Simple utility to check the status of Plex's built-in scheduled
#              backups that replaced the custom backup system.
#
# Usage:
#   ./check-plex-builtin-backups.sh          # Show backup status
#   ./check-plex-builtin-backups.sh --help   # Show help
#
################################################################################

# Color codes
GREEN=$'\033[0;32m'
YELLOW=$'\033[1;33m'
BLUE=$'\033[0;34m'
RED=$'\033[0;31m'
NC=$'\033[0m' # No Color

# Plex database path
PLEX_DB_PATH="/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases"
NAS_BACKUP_PATH="/mnt/share/media/backups/plex"

show_help() {
    echo "Plex Built-in Backup Status Checker"
    echo ""
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --help, -h    Show this help message"
    echo "  --detailed    Show detailed file information"
    echo ""
    echo "This script checks the status of Plex's built-in scheduled backups"
    echo "which replaced the custom backup system on June 21, 2025."
    echo ""
    echo "Plex automatically creates backups every 3 days with pattern:"
    echo "  *.backup.YYYYMMDD_HHMMSS"
    echo ""
    exit 0
}

check_backup_status() {
    local detailed="${1:-false}"
    
    echo -e "${BLUE}===============================================${NC}"
    echo -e "${BLUE}  Plex Built-in Backup Status Check${NC}"
    echo -e "${BLUE}===============================================${NC}"
    echo ""
    
    # Check if Plex database directory exists
    if [ ! -d "$PLEX_DB_PATH" ]; then
        echo -e "${RED}❌ Error: Plex database directory not found${NC}"
        echo -e "   Expected: $PLEX_DB_PATH"
        return 1
    fi
    
    echo -e "${GREEN}✅ Plex database directory found${NC}"
    echo -e "   Location: $PLEX_DB_PATH"
    echo ""
    
    # Check for built-in backup files
    local backup_files
    backup_files=$(find "$PLEX_DB_PATH" -name "*.backup.*" 2>/dev/null)
    
    if [ -z "$backup_files" ]; then
        echo -e "${YELLOW}⚠️  No built-in backup files found${NC}"
        echo -e "   This might indicate Plex backups haven't run yet"
        echo -e "   or the backup schedule is not configured."
        echo ""
    else
        local backup_count
        backup_count=$(echo "$backup_files" | wc -l)
        echo -e "${GREEN}✅ Found $backup_count built-in backup file(s)${NC}"
        echo ""
        
        # Show latest backup
        local latest_backup
        latest_backup=$(echo "$backup_files" | xargs -I {} ls -t {} | head -1)
        if [ -n "$latest_backup" ]; then
            local backup_date
            backup_date=$(stat -c %y "$latest_backup" 2>/dev/null | cut -d' ' -f1,2 | cut -d'.' -f1)
            local backup_size
            backup_size=$(du -h "$latest_backup" 2>/dev/null | cut -f1)
            
            echo -e "${GREEN}📅 Latest backup:${NC}"
            echo -e "   File: $(basename "$latest_backup")"
            echo -e "   Date: $backup_date"
            echo -e "   Size: $backup_size"
            echo ""
        fi
        
        # Show detailed info if requested
        if [ "$detailed" = true ]; then
            echo -e "${BLUE}📋 All backup files:${NC}"
            echo "$backup_files" | while IFS= read -r file; do
                if [ -f "$file" ]; then
                    ls -lah "$file" 2>/dev/null | while IFS= read -r line; do
                        echo "   $line"
                    done
                fi
            done
            echo ""
        fi
        
        # Check backup frequency (should be every 3 days)
        if [ "$backup_count" -ge 2 ]; then
            local newest_backup
            local second_newest_backup
            newest_backup=$(echo "$backup_files" | xargs -I {} ls -t {} | head -1)
            second_newest_backup=$(echo "$backup_files" | xargs -I {} ls -t {} | head -2 | tail -1)
            
            if [ -n "$newest_backup" ] && [ -n "$second_newest_backup" ]; then
                local newest_time
                local second_time
                newest_time=$(stat -c %Y "$newest_backup" 2>/dev/null)
                second_time=$(stat -c %Y "$second_newest_backup" 2>/dev/null)
                
                if [ -n "$newest_time" ] && [ -n "$second_time" ]; then
                    local time_diff=$((newest_time - second_time))
                    local days_diff=$((time_diff / 86400))
                    
                    echo -e "${BLUE}⏱️  Backup frequency check:${NC}"
                    echo -e "   Days between last two backups: $days_diff"
                    if [ "$days_diff" -ge 2 ] && [ "$days_diff" -le 4 ]; then
                        echo -e "   ${GREEN}✅ Frequency looks normal (every ~3 days)${NC}"
                    else
                        echo -e "   ${YELLOW}⚠️  Frequency might be unusual${NC}"
                    fi
                    echo ""
                fi
            fi
        fi
    fi
    
    # Check NAS backup location
    echo -e "${BLUE}📁 NAS Backup Location Check:${NC}"
    if [ -d "$NAS_BACKUP_PATH" ]; then
        echo -e "${GREEN}✅ NAS backup directory accessible${NC}"
        echo -e "   Location: $NAS_BACKUP_PATH"
        
        local old_custom_backups
        old_custom_backups=$(find "$NAS_BACKUP_PATH" -name "plex-backup-*.tar.gz" 2>/dev/null | wc -l)
        if [ "$old_custom_backups" -gt 0 ]; then
            echo -e "   ${YELLOW}📦 Found $old_custom_backups legacy custom backup files${NC}"
            echo -e "   ${YELLOW}   (These are from the old custom backup system)${NC}"
        fi
    else
        echo -e "${RED}❌ NAS backup directory not accessible${NC}"
        echo -e "   Expected: $NAS_BACKUP_PATH"
    fi
    echo ""
    
    # Summary
    echo -e "${BLUE}📊 Summary:${NC}"
    echo -e "${GREEN}✅ Custom backup system: DISABLED (June 21, 2025)${NC}"
    echo -e "${GREEN}✅ Plex built-in backups: ACTIVE${NC}"
    echo -e "${BLUE}ℹ️  Backup frequency: Every 3 days (automatic)${NC}"
    echo -e "${BLUE}ℹ️  Manual tools available: plex-db-manager.sh, plex.sh${NC}"
    echo ""
}

# Parse command line arguments
case "${1:-}" in
    --help|-h)
        show_help
        ;;
    --detailed)
        check_backup_status true
        ;;
    "")
        check_backup_status false
        ;;
    *)
        echo "Unknown option: $1"
        echo "Use --help for usage information"
        exit 1
        ;;
esac
