#!/bin/bash ################################################################################ # Script: remove-media.sh # Description: Remove media files and XML entries from ROM collections to reduce # storage space for SD cards and portable devices. Supports Batocera, # Rocknix, RetroPie, and other EmulationStation-based systems. # # Usage: ./remove-media.sh [OPTIONS] # # Arguments: # system_path Path to ROM system directory containing media/ folder # # Options: # Media Types: # --boxart Remove boxart/cover images # --cartridge Remove cartridge images # --image Remove general images # --manual Remove game manuals # --marquee Remove arcade marquee images # --mix Remove mix media files # --screenshot Remove game screenshots # --video Remove game videos # --wheel Remove wheel/logo images # --all-media Remove all media types # # Operation Modes: # --dry-run Preview changes without executing them # --force Skip confirmation prompts # # Output Options: # --verbose Show detailed progress information # --quiet Show minimal output # --no-progress Disable progress indicators # # Help: # --help, -h Show this help message # # Examples: # ./remove-media.sh --boxart --video /path/to/nes # ./remove-media.sh --all-media --dry-run /data/emu/org/nes # ./remove-media.sh --screenshot --marquee --force ./collections/snes # # Dependencies: # - xmlstarlet (for XML processing) # - find, rm (core utilities) # # Features: # - Dry-run mode for safe preview # - Progress indicators for large collections # - Space savings calculation # - Backup recommendations # - XML validation and cleanup # - Support for multiple EmulationStation variants ################################################################################ # Script identification SCRIPT_NAME="remove-media.sh" # Set umask to 000 to ensure files are created with 666 permissions umask 000 # Determine the directory of the current script SCRIPT_DIR="$(dirname "$(realpath "$0")")" # Determine the project root directory PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" # Load configuration and utilities from the script's directory source "${PROJECT_ROOT}/core/config.sh" source "${PROJECT_ROOT}/core/logger.sh" source "${PROJECT_ROOT}/core/utils.sh" source "${PROJECT_ROOT}/core/progress.sh" # Log the script name when it is called log "DEBUG" "Starting script: $(basename "$0")" # Global variables SYSTEM_PATH="" MEDIA_TYPES=() DRY_RUN=false FORCE_MODE=false VERBOSE=false QUIET=false NO_PROGRESS=false # All available media types ALL_MEDIA_TYPES=("boxart" "cartridge" "image" "manual" "marquee" "mix" "screenshot" "video" "wheel") # Media type descriptions for user-friendly output declare -A MEDIA_DESCRIPTIONS=( ["boxart"]="Box art/cover images" ["cartridge"]="Cartridge images" ["image"]="General images" ["manual"]="Game manuals" ["marquee"]="Arcade marquee images" ["mix"]="Mix media files" ["screenshot"]="Game screenshots" ["video"]="Game videos" ["wheel"]="Wheel/logo images" ) # Statistics tracking TOTAL_FILES_REMOVED=0 TOTAL_SPACE_SAVED=0 TOTAL_XML_ENTRIES_REMOVED=0 # Function to display usage information show_usage() { cat << 'EOF' Usage: ./remove-media.sh [OPTIONS] Remove media files and XML entries from ROM collections to reduce storage space. Designed for SD cards and portable EmulationStation-based systems. Arguments: system_path Path to ROM system directory containing media/ folder Media Types: --boxart Remove boxart/cover images --cartridge Remove cartridge images --image Remove general images --manual Remove game manuals --marquee Remove arcade marquee images --mix Remove mix media files --screenshot Remove game screenshots --video Remove game videos --wheel Remove wheel/logo images --all-media Remove all media types Operation Modes: --dry-run Preview changes without executing them --force Skip confirmation prompts Output Options: --verbose Show detailed progress information --quiet Show minimal output --no-progress Disable progress indicators Help: --help, -h Show this help message Examples: ./remove-media.sh --boxart --video /path/to/nes ./remove-media.sh --all-media --dry-run /data/emu/org/nes ./remove-media.sh --screenshot --marquee --force ./collections/snes Dependencies: - xmlstarlet (for XML processing) - find, rm (core utilities) EOF } # Function to validate system path validate_system_path() { local path="$1" if [[ -z "$path" ]]; then log "ERROR" "System path is required" return 1 fi if [[ ! -d "$path" ]]; then log "ERROR" "System path does not exist: $path" return 1 fi if [[ ! -r "$path" ]]; then log "ERROR" "System path is not readable: $path" return 1 fi # Check for media directory if [[ ! -d "$path/media" ]]; then log "WARN" "No media directory found at: $path/media" log "INFO" "This system may not have any media files to remove" fi # Check for gamelist.xml if [[ ! -f "$path/gamelist.xml" ]]; then log "WARN" "No gamelist.xml found at: $path/gamelist.xml" log "INFO" "XML cleanup will be skipped" fi return 0 } # Function to check dependencies check_dependencies() { local missing_deps=() # Check for required tools if ! command -v find >/dev/null 2>&1; then missing_deps+=("find") fi if ! command -v rm >/dev/null 2>&1; then missing_deps+=("rm") fi # Check for xmlstarlet (optional but recommended) if ! command -v xmlstarlet >/dev/null 2>&1; then log "WARN" "xmlstarlet not found - XML cleanup will be skipped" log "INFO" "Install xmlstarlet for full functionality: apt-get install xmlstarlet" fi if [[ ${#missing_deps[@]} -gt 0 ]]; then log "ERROR" "Missing required dependencies: ${missing_deps[*]}" log "INFO" "Please install missing tools and try again" return 1 fi return 0 } # Function to calculate directory size calculate_directory_size() { local dir="$1" if [[ ! -d "$dir" ]]; then echo "0" return fi # Use du to get size in bytes local size=$(du -sb "$dir" 2>/dev/null | cut -f1) echo "${size:-0}" } # Function to format file size for human readable output format_file_size() { local bytes=$1 local units=("B" "KB" "MB" "GB" "TB") local unit=0 local size=$bytes while [[ $size -gt 1024 && $unit -lt $((${#units[@]} - 1)) ]]; do size=$((size / 1024)) ((unit++)) done printf "%.1f %s" "$size" "${units[$unit]}" } # Function to count files in directory count_files_in_directory() { local dir="$1" if [[ ! -d "$dir" ]]; then echo "0" return fi find "$dir" -type f 2>/dev/null | wc -l } # Function to show media analysis show_media_analysis() { local system_path="$1" if [[ $QUIET == true ]]; then return fi log "INFO" "Analyzing media in: $system_path" echo "" local total_size=0 local total_files=0 printf "%-12s %-20s %-10s %-10s\n" "Type" "Description" "Files" "Size" printf "%-12s %-20s %-10s %-10s\n" "----" "-----------" "-----" "----" for media_type in "${ALL_MEDIA_TYPES[@]}"; do local media_path="$system_path/media/$media_type" local file_count=$(count_files_in_directory "$media_path") local dir_size=$(calculate_directory_size "$media_path") local formatted_size=$(format_file_size "$dir_size") if [[ $file_count -gt 0 ]]; then printf "%-12s %-20s %-10d %-10s\n" \ "$media_type" "${MEDIA_DESCRIPTIONS[$media_type]}" "$file_count" "$formatted_size" total_files=$((total_files + file_count)) total_size=$((total_size + dir_size)) fi done if [[ $total_files -gt 0 ]]; then echo "" printf "%-12s %-20s %-10d %-10s\n" \ "TOTAL" "All media types" "$total_files" "$(format_file_size $total_size)" else log "INFO" "No media files found in this system" fi echo "" } # Function to remove media files from directory remove_media_files() { local media_type="$1" local system_path="$2" local media_path="$system_path/media/$media_type" # Check if media directory exists if [[ ! -d "$media_path" ]]; then if [[ $VERBOSE == true ]]; then log "DEBUG" "No $media_type directory found at: $media_path" fi return 0 fi # Validate path is within expected location if [[ "$media_path" != "$system_path/media/"* ]]; then log "ERROR" "Invalid media path detected: $media_path" return 1 fi # Count files before removal local file_count=$(count_files_in_directory "$media_path") if [[ $file_count -eq 0 ]]; then if [[ $VERBOSE == true ]]; then log "DEBUG" "No files found in $media_type directory" fi return 0 fi # Calculate size before removal local dir_size_before=$(calculate_directory_size "$media_path") if [[ $DRY_RUN == true ]]; then log "INFO" "[DRY-RUN] Would remove $file_count ${MEDIA_DESCRIPTIONS[$media_type]} files ($(format_file_size $dir_size_before))" TOTAL_FILES_REMOVED=$((TOTAL_FILES_REMOVED + file_count)) TOTAL_SPACE_SAVED=$((TOTAL_SPACE_SAVED + dir_size_before)) return 0 fi log "INFO" "Removing $file_count ${MEDIA_DESCRIPTIONS[$media_type]} files..." # Remove files with progress tracking if enabled if [[ $NO_PROGRESS == false && $file_count -gt 5 ]]; then progress_batch_start "Removing $media_type files" "$file_count" local current=0 while IFS= read -r -d '' file; do if [[ $VERBOSE == true ]]; then progress_batch_update "$(basename "$file")" "processing" fi if rm -f "$file" 2>/dev/null; then ((current++)) progress_batch_update "$(basename "$file")" "success" else log "WARN" "Failed to remove: $file" progress_batch_update "$(basename "$file")" "failed" fi done < <(find "$media_path" -type f -print0) progress_batch_finish "completed" else # Simple removal without progress bar find "$media_path" -type f -delete 2>/dev/null fi # Update statistics local dir_size_after=$(calculate_directory_size "$media_path") local space_saved=$((dir_size_before - dir_size_after)) TOTAL_FILES_REMOVED=$((TOTAL_FILES_REMOVED + file_count)) TOTAL_SPACE_SAVED=$((TOTAL_SPACE_SAVED + space_saved)) log "INFO" "Removed $file_count files, saved $(format_file_size $space_saved)" # Remove empty directory if rmdir "$media_path" 2>/dev/null; then if [[ $VERBOSE == true ]]; then log "DEBUG" "Removed empty directory: $media_path" fi fi return 0 } # Function to remove XML entries remove_xml_entries() { local media_type="$1" local system_path="$2" local gamelist_file="$system_path/gamelist.xml" # Check if gamelist.xml exists if [[ ! -f "$gamelist_file" ]]; then if [[ $VERBOSE == true ]]; then log "DEBUG" "No gamelist.xml found - skipping XML cleanup" fi return 0 fi # Check if xmlstarlet is available if ! command -v xmlstarlet >/dev/null 2>&1; then if [[ $VERBOSE == true ]]; then log "DEBUG" "xmlstarlet not available - skipping XML cleanup" fi return 0 fi # Count existing entries local entry_count=$(xmlstarlet sel -t -v "count(//game/$media_type)" "$gamelist_file" 2>/dev/null || echo "0") if [[ $entry_count -eq 0 ]]; then if [[ $VERBOSE == true ]]; then log "DEBUG" "No $media_type XML entries found" fi return 0 fi if [[ $DRY_RUN == true ]]; then log "INFO" "[DRY-RUN] Would remove $entry_count $media_type XML entries" TOTAL_XML_ENTRIES_REMOVED=$((TOTAL_XML_ENTRIES_REMOVED + entry_count)) return 0 fi # Create backup of gamelist.xml if ! cp "$gamelist_file" "$gamelist_file.backup.$(date +%Y%m%d_%H%M%S)" 2>/dev/null; then log "WARN" "Could not create backup of gamelist.xml" fi # Remove XML entries if xmlstarlet ed -L -d "//game/$media_type" "$gamelist_file" 2>/dev/null; then log "INFO" "Removed $entry_count $media_type XML entries" TOTAL_XML_ENTRIES_REMOVED=$((TOTAL_XML_ENTRIES_REMOVED + entry_count)) else log "ERROR" "Failed to remove $media_type XML entries" return 1 fi return 0 } # Function to process a single media type process_media_type() { local media_type="$1" local system_path="$2" if [[ $VERBOSE == true ]]; then log "DEBUG" "Processing media type: $media_type" fi # Remove media files if ! remove_media_files "$media_type" "$system_path"; then log "ERROR" "Failed to remove $media_type files" return 1 fi # Remove XML entries if ! remove_xml_entries "$media_type" "$system_path"; then log "ERROR" "Failed to remove $media_type XML entries" return 1 fi return 0 } # Function to confirm operation confirm_operation() { if [[ $FORCE_MODE == true || $DRY_RUN == true ]]; then return 0 fi echo "" log "WARN" "This operation will permanently remove media files!" log "INFO" "System path: $SYSTEM_PATH" log "INFO" "Media types: ${MEDIA_TYPES[*]}" echo "" log "INFO" "It is recommended to backup your collection before proceeding." echo "" read -p "Continue with media removal? (y/N): " -r if [[ ! $REPLY =~ ^[Yy]$ ]]; then log "INFO" "Operation cancelled by user" return 1 fi return 0 } # Function to show final summary show_summary() { if [[ $QUIET == true ]]; then return fi echo "" log "INFO" "=== Media Removal Summary ===" if [[ $DRY_RUN == true ]]; then log "INFO" "DRY-RUN MODE - No changes were made" echo "" log "INFO" "Would remove:" else log "INFO" "Successfully removed:" fi echo " • $TOTAL_FILES_REMOVED media files" echo " • $TOTAL_XML_ENTRIES_REMOVED XML entries" echo " • $(format_file_size $TOTAL_SPACE_SAVED) of storage space" if [[ $DRY_RUN == true ]]; then echo "" log "INFO" "Run without --dry-run to perform actual removal" fi echo "" } # Function to parse command line arguments parse_arguments() { local positional_args=() while [[ $# -gt 0 ]]; do case $1 in # Media type flags --boxart|--cartridge|--image|--manual|--marquee|--mix|--screenshot|--video|--wheel) local media_type="${1#--}" MEDIA_TYPES+=("$media_type") ;; --all-media) MEDIA_TYPES=("${ALL_MEDIA_TYPES[@]}") ;; # Operation mode flags --dry-run) DRY_RUN=true ;; --force) FORCE_MODE=true ;; # Output control flags --verbose) VERBOSE=true ;; --quiet) QUIET=true ;; --no-progress) NO_PROGRESS=true ;; # Help --help|-h) show_usage exit 0 ;; # Legacy --path support (for backward compatibility) --path) if [[ -n "$2" && "$2" != --* ]]; then positional_args+=("$2") shift else log "ERROR" "--path requires a directory argument" exit 1 fi ;; # Unknown option --*) log "ERROR" "Unknown option: $1" log "INFO" "Use --help for usage information" exit 1 ;; # Positional argument (system path) *) positional_args+=("$1") ;; esac shift done # Process positional arguments if [[ ${#positional_args[@]} -eq 0 ]]; then log "ERROR" "System path is required" log "INFO" "Use --help for usage information" exit 1 elif [[ ${#positional_args[@]} -gt 1 ]]; then log "ERROR" "Multiple system paths specified: ${positional_args[*]}" log "INFO" "Please specify only one system path" exit 1 fi SYSTEM_PATH="${positional_args[0]}" # Validate that at least one media type is specified if [[ ${#MEDIA_TYPES[@]} -eq 0 ]]; then log "ERROR" "No media types specified" log "INFO" "Use --help to see available media types" exit 1 fi # Conflicting options if [[ $VERBOSE == true && $QUIET == true ]]; then log "ERROR" "Cannot use --verbose and --quiet together" exit 1 fi return 0 } # Main function main() { # Parse command line arguments parse_arguments "$@" # Set logging level based on verbosity if [[ $QUIET == true ]]; then LOG_LEVEL="ERROR" elif [[ $VERBOSE == true ]]; then LOG_LEVEL="DEBUG" fi # Initialize progress system if not disabled if [[ $NO_PROGRESS == false ]]; then progress_init fi # Check dependencies if ! check_dependencies; then exit 1 fi # Validate system path if ! validate_system_path "$SYSTEM_PATH"; then exit 1 fi # Show media analysis show_media_analysis "$SYSTEM_PATH" # Confirm operation if ! confirm_operation; then exit 0 fi # Process each media type local success=true for media_type in "${MEDIA_TYPES[@]}"; do if ! process_media_type "$media_type" "$SYSTEM_PATH"; then success=false fi done # Show summary show_summary if [[ $success == true ]]; then if [[ $DRY_RUN == true ]]; then log "INFO" "Dry-run completed successfully" else log "INFO" "Media removal completed successfully" fi exit 0 else log "ERROR" "Media removal completed with errors" exit 1 fi } # Show usage if called with --help even in non-interactive mode if [[ "$1" == "--help" || "$1" == "-h" ]]; then show_usage exit 0 fi # Run the main function with all arguments main "$@"