#!/bin/bash ################################################################################ # Script: scan-archives.sh # Description: Scans ROM archive directories to identify and optionally remove # problematic files that cause issues in ROM collections. # # Usage: ./scan-archives.sh [options] # # Dependencies: # - config.sh # - logger.sh # - unzip (for ZIP files) # - 7z (for 7Z files) # - rar (for RAR files) # # Features: # - Tests archive integrity and identifies corrupted files # - Detects case-insensitive filename collisions (Windows compatibility) # - Interactive deletion prompts with batch options # - Comprehensive logging and reporting # - Support for multiple archive formats # # Examples: # ./scan-archives.sh /data/emu/org/nes.usa.1g1r/ # ./scan-archives.sh /data/emu/filter/snes/ --auto-delete-corrupted # ./scan-archives.sh /path/to/roms/ --report-only ################################################################################ # Script identification SCRIPT_NAME="scan-archives.sh" # Global variables declare -a CORRUPTED_FILES declare -a COLLISION_FILES declare -A ARCHIVE_EXTENSIONS declare -A TESTED_FILES declare -i MAX_PARALLEL_JOBS=4 declare -i CORRUPTION_TESTS=0 declare -i COLLISION_CHECKS=0 declare -i TOTAL_ARCHIVES=0 declare -i CORRUPTED_COUNT=0 declare -i COLLISION_FILES_COUNT=0 # Supported archive formats and their test commands ARCHIVE_EXTENSIONS=( ["zip"]="unzip -t" ["7z"]="7z t" ["rar"]="unrar t" ["tar"]="tar -tf" ["gz"]="gunzip -t" ["bz2"]="bunzip2 -t" ["xz"]="xz -t" ["lz"]="lzip -t" ["lzma"]="lzma -t" ["z"]="uncompress -t" ) # Command line options FIX_COLLISIONS=false REMOVE_CORRUPTED=false DRY_RUN=false VERBOSE=false # 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 logger from the script's directory source "${PROJECT_ROOT}/core/config.sh" source "${PROJECT_ROOT}/core/logger.sh" # Log the script name when it is called log "DEBUG" "Starting script: $(basename "$0")" # Function to display usage information show_usage() { echo "Usage: $0 [options]" echo "" echo "Scans ROM archive directories for corruption and filename collisions." echo "" echo "Parameters:" echo " Path to directory containing archive files to scan" echo "" echo "Options:" echo " --fix-collisions Interactively remove case-collision duplicates" echo " --remove-corrupted Interactively remove corrupted archives" echo " --parallel Set parallel jobs (1-8, default: 4)" echo " --dry-run Show what would be done without making changes" echo " --verbose Enable verbose output" echo " --help Show this help message" echo "" echo "Archive Support:" echo " - ZIP files (.zip)" echo " - 7-Zip archives (.7z)" echo " - RAR archives (.rar)" echo " - TAR archives (.tar, .tar.gz, .tar.bz2, .tar.xz)" echo " - Compressed files (.gz, .bz2, .xz, .lz, .lzma, .z)" echo "" echo "Detection Features:" echo " - Corruption testing using native archive tools" echo " - Case-insensitive filename collision detection" echo " - Parallel processing for faster scanning" echo " - Interactive deletion with confirmation prompts" echo "" echo "Examples:" echo " $0 /data/emu/org/nes.usa.1g1r/ # Scan only" echo " $0 /data/emu/org/snes.usa.1g1r/ --fix-collisions # Fix collisions" echo " $0 /path/to/roms/ --remove-corrupted # Remove corrupted" echo " $0 /path/to/roms/ --fix-collisions --remove-corrupted # Fix both" echo "" echo "Note: This tool helps maintain clean ROM collections by identifying" echo " problematic archives that cause issues on different filesystems." echo "" echo "Related Tools:" echo " verify-and-clean-roms-zips.sh - For ROM-specific DAT validation and hash verification" } # Function to parse command line arguments parse_arguments() { local input_dir="" while [[ $# -gt 0 ]]; do case $1 in --fix-collisions) FIX_COLLISIONS=true shift ;; --remove-corrupted) REMOVE_CORRUPTED=true shift ;; --parallel) if [[ -n "$2" && "$2" =~ ^[1-8]$ ]]; then MAX_PARALLEL_JOBS="$2" shift 2 else log "ERROR" "Invalid parallel jobs count. Must be 1-8." exit 1 fi ;; --dry-run) DRY_RUN=true shift ;; --verbose) VERBOSE=true LOG_LEVEL="DEBUG" shift ;; --help|-h) show_usage exit 0 ;; -*) log "ERROR" "Unknown option: $1" show_usage exit 1 ;; *) if [[ -z "$input_dir" ]]; then input_dir="$1" else log "ERROR" "Multiple directories specified: $input_dir and $1" show_usage exit 1 fi shift ;; esac done if [[ -z "$input_dir" ]]; then log "ERROR" "No directory specified" show_usage exit 1 fi echo "$input_dir" } # Function to validate input directory validate_input() { local input_dir="$1" if [[ ! -d "$input_dir" ]]; then log "ERROR" "Directory does not exist: $input_dir" exit 1 fi if [[ ! -r "$input_dir" ]]; then log "ERROR" "Directory is not readable: $input_dir" exit 1 fi if [[ ! "$DRY_RUN" == "true" && ! -w "$input_dir" ]]; then log "ERROR" "Directory is not writable: $input_dir (required for deletion operations)" exit 1 fi log "INFO" "Input directory validated: $input_dir" } # Function to check if required tools are available check_dependencies() { local missing_tools=() local available_formats=() log "INFO" "Checking archive tool dependencies" # Check each archive tool for ext in "${!ARCHIVE_EXTENSIONS[@]}"; do local tool_cmd="${ARCHIVE_EXTENSIONS[$ext]%% *}" # Get first word (tool name) if command -v "$tool_cmd" >/dev/null 2>&1; then available_formats+=("$ext") log "DEBUG" "Found tool for .$ext files: $tool_cmd" else missing_tools+=("$tool_cmd") log "WARN" "Missing tool for .$ext files: $tool_cmd" fi done if [[ ${#available_formats[@]} -eq 0 ]]; then log "ERROR" "No archive tools found. Please install at least one of: ${missing_tools[*]}" exit 1 fi log "INFO" "Available archive formats: ${available_formats[*]}" if [[ ${#missing_tools[@]} -gt 0 ]]; then log "WARN" "Missing tools (optional): ${missing_tools[*]}" fi } # Function to identify archive files in directory find_archives() { local input_dir="$1" local -a archive_files log "INFO" "Scanning for archive files in: $input_dir" # Find archive files (case-insensitive) while IFS= read -r file; do if [[ -f "$file" ]]; then archive_files+=("$file") fi done < <(find "$input_dir" -maxdepth 1 -type f \( \ -iname "*.zip" -o \ -iname "*.7z" -o \ -iname "*.rar" -o \ -iname "*.gz" -o \ -iname "*.bz2" \ \)) TOTAL_ARCHIVES=${#archive_files[@]} if [[ $TOTAL_ARCHIVES -eq 0 ]]; then log "WARN" "No archive files found in directory: $input_dir" echo "No archive files found to scan." exit 0 fi log "INFO" "Found $TOTAL_ARCHIVES archive files to scan" echo "Found $TOTAL_ARCHIVES archive files to scan." # Output the files for processing printf '%s\n' "${archive_files[@]}" } # Function to test archive integrity test_archive_integrity() { local file="$1" local filename local extension local result filename=$(basename "$file") extension="${filename##*.}" extension=$(echo "$extension" | tr '[:upper:]' '[:lower:]') log "DEBUG" "Testing integrity of: $filename" case "$extension" in zip) if unzip -t "$file" >/dev/null 2>&1; then result="OK" else result="CORRUPTED" fi ;; 7z) if 7z t "$file" >/dev/null 2>&1; then result="OK" else result="CORRUPTED" fi ;; rar) if command -v rar >/dev/null 2>&1; then if rar t "$file" >/dev/null 2>&1; then result="OK" else result="CORRUPTED" fi else result="SKIPPED" fi ;; gz|bz2) # For single-file compressed archives, try to test with 7z if 7z t "$file" >/dev/null 2>&1; then result="OK" else result="CORRUPTED" fi ;; *) result="UNSUPPORTED" ;; esac echo "$result" } # Function to get archive extension from filename get_archive_extension() { local filename="$1" local ext # Handle compound extensions first if [[ "$filename" =~ \.tar\.(gz|bz2|xz)$ ]]; then echo "tar" return fi # Get the last extension ext="${filename##*.}" ext="${ext,,}" # Convert to lowercase # Check if it's a supported format if [[ -n "${ARCHIVE_EXTENSIONS[$ext]:-}" ]]; then echo "$ext" else echo "" fi } # Function to test if an archive is corrupted test_archive_corruption() { local filepath="$1" local filename="$2" local ext local test_cmd local result_file ext=$(get_archive_extension "$filename") if [[ -z "$ext" ]]; then return 0 # Not an archive, skip fi test_cmd="${ARCHIVE_EXTENSIONS[$ext]}" if [[ -z "$test_cmd" ]]; then log "WARN" "No test command available for extension: $ext" return 0 fi # Create temporary result file result_file=$(mktemp) log "DEBUG" "Testing archive: $filename" # Test the archive and capture output if $test_cmd "$filepath" >/dev/null 2>"$result_file"; then rm -f "$result_file" return 0 # Archive is good else local error_output error_output=$(cat "$result_file" 2>/dev/null || echo "Unknown error") rm -f "$result_file" log "WARN" "Corrupted archive detected: $filename - $error_output" return 1 # Archive is corrupted fi } # Function to scan for corrupted archives using parallel processing scan_corrupted_archives() { local input_dir="$1" local temp_dir local job_count=0 log "INFO" "Scanning for corrupted archives with $MAX_PARALLEL_JOBS parallel jobs" # Create temporary directory for parallel processing temp_dir=$(mktemp -d) # Count archives to be tested CORRUPTION_TESTS=0 while IFS= read -r file; do local filename filename=$(basename "$file") # Skip if not an archive if [[ -z "$(get_archive_extension "$filename")" ]]; then continue fi ((CORRUPTION_TESTS++)) done < <(find "$input_dir" -maxdepth 1 -type f) # Process files in parallel while IFS= read -r file; do local filename filename=$(basename "$file") # Skip if not an archive if [[ -z "$(get_archive_extension "$filename")" ]]; then continue fi # Launch background job ( if test_archive_corruption "$file" "$filename" >/dev/null 2>&1; then # Archive is good, do nothing : else # Archive is corrupted, add to list echo "$file" >> "$temp_dir/corrupted.txt" fi ) & ((job_count++)) # Limit parallel jobs if (( job_count >= MAX_PARALLEL_JOBS )); then wait # Wait for all background jobs to complete job_count=0 fi done < <(find "$input_dir" -maxdepth 1 -type f) # Wait for remaining jobs wait # Collect results if [[ -f "$temp_dir/corrupted.txt" ]]; then mapfile -t CORRUPTED_FILES < "$temp_dir/corrupted.txt" fi # Cleanup rm -rf "$temp_dir" log "INFO" "Corruption scan completed: ${#CORRUPTED_FILES[@]} corrupted files found, $CORRUPTION_TESTS archives tested" } # Function to detect case-insensitive filename collisions scan_filename_collisions() { local input_dir="$1" local -A lowercase_files log "INFO" "Scanning for case-insensitive filename collisions" # Build lowercase filename map while IFS= read -r file; do local filename local lowercase_name filename=$(basename "$file") lowercase_name="${filename,,}" # Convert to lowercase if [[ -n "${lowercase_files[$lowercase_name]:-}" ]]; then # Collision detected - add both files to collision list local existing_file="${lowercase_files[$lowercase_name]}" local existing_filename existing_filename=$(basename "$existing_file") # Only add if filenames are actually different (not same file) if [[ "$filename" != "$existing_filename" ]]; then log "WARN" "Case collision detected: '$existing_filename' vs '$filename'" # Add both files to collision list if not already added if ! printf '%s\n' "${COLLISION_FILES[@]}" | grep -Fxq "$existing_file"; then COLLISION_FILES+=("$existing_file") fi if ! printf '%s\n' "${COLLISION_FILES[@]}" | grep -Fxq "$file"; then COLLISION_FILES+=("$file") fi ((COLLISION_CHECKS++)) fi else lowercase_files["$lowercase_name"]="$file" fi done < <(find "$input_dir" -maxdepth 1 -type f) log "INFO" "Collision scan completed: ${#COLLISION_FILES[@]} files with case collisions found" } # Function to scan all archives scan_archives() { local input_dir="$1" local -a archive_files local progress=0 # Get list of archive files mapfile -t archive_files < <(find_archives "$input_dir") echo "" echo "=== ARCHIVE INTEGRITY SCAN ===" # Test each archive for file in "${archive_files[@]}"; do ((progress++)) local filename=$(basename "$file") local integrity_result if [[ "$VERBOSE" == "true" ]]; then echo "[$progress/$TOTAL_ARCHIVES] Testing: $filename" else echo -ne "\\rTesting archives... [$progress/$TOTAL_ARCHIVES]" fi integrity_result=$(test_archive_integrity "$file") case "$integrity_result" in CORRUPTED) CORRUPTED_FILES+=("$file") ((CORRUPTED_COUNT++)) log "WARN" "Corrupted archive detected: $filename" if [[ "$VERBOSE" == "true" ]]; then echo " ❌ CORRUPTED" fi ;; OK) log "DEBUG" "Archive integrity OK: $filename" if [[ "$VERBOSE" == "true" ]]; then echo " ✅ OK" fi ;; SKIPPED) log "DEBUG" "Archive skipped (unsupported): $filename" if [[ "$VERBOSE" == "true" ]]; then echo " ⏭️ SKIPPED" fi ;; UNSUPPORTED) log "DEBUG" "Unsupported archive format: $filename" if [[ "$VERBOSE" == "true" ]]; then echo " ❓ UNSUPPORTED" fi ;; esac done if [[ "$VERBOSE" == "false" ]]; then echo "" # New line after progress indicator fi echo "" echo "=== CASE COLLISION DETECTION ===" # Detect case collisions local collision_data mapfile -t collision_data < <(detect_case_collisions "$input_dir") for collision_group in "${collision_data[@]}"; do IFS='|' read -ra files <<< "$collision_group" if [[ ${#files[@]} -gt 1 ]]; then CASE_COLLISION_GROUPS+=("$collision_group") COLLISION_FILES_COUNT=$((COLLISION_FILES_COUNT + ${#files[@]})) log "WARN" "Case collision detected: ${files[*]}" if [[ "$VERBOSE" == "true" ]]; then echo "Case collision group:" for file in "${files[@]}"; do echo " - $(basename "$file")" done fi fi done } # Function to display scan results display_results() { echo "" echo "=== SCAN RESULTS ===" echo "Total archives scanned: $TOTAL_ARCHIVES" echo "Corrupted archives: $CORRUPTED_COUNT" echo "Case collision files: $COLLISION_FILES_COUNT" echo "Case collision groups: ${#CASE_COLLISION_GROUPS[@]}" if [[ $CORRUPTED_COUNT -gt 0 ]]; then echo "" echo "Corrupted archives found:" for file in "${CORRUPTED_FILES[@]}"; do echo " ❌ $(basename "$file")" done fi if [[ ${#CASE_COLLISION_GROUPS[@]} -gt 0 ]]; then echo "" echo "Case collision groups found:" for group in "${CASE_COLLISION_GROUPS[@]}"; do echo " Collision group:" IFS='|' read -ra files <<< "$group" for file in "${files[@]}"; do echo " - $(basename "$file")" done done fi } # Function to prompt for file deletion prompt_for_deletion() { local file_type="$1" local -a files_to_delete case "$file_type" in corrupted) if [[ $CORRUPTED_COUNT -eq 0 ]]; then return 0 fi files_to_delete=("${CORRUPTED_FILES[@]}") ;; collisions) if [[ ${#CASE_COLLISION_GROUPS[@]} -eq 0 ]]; then return 0 fi # Build list of collision files (keeping first in each group) for group in "${CASE_COLLISION_GROUPS[@]}"; do IFS='|' read -ra files <<< "$group" # Skip first file, add rest to deletion list for ((i=1; i<${#files[@]}; i++)); do files_to_delete+=("${files[$i]}") done done ;; esac if [[ ${#files_to_delete[@]} -eq 0 ]]; then return 0 fi echo "" echo "Do you want to delete these $file_type files? (${#files_to_delete[@]} files)" echo "Options:" echo " y/yes - Delete all" echo " n/no - Keep all" echo " i/interactive - Choose individually" echo " l/list - Show file list" while true; do read -r -p "Choice [y/n/i/l]: " choice case "$choice" in y|yes|Y|YES) delete_files "${files_to_delete[@]}" break ;; n|no|N|NO) echo "Keeping all $file_type files." break ;; i|interactive|I|INTERACTIVE) interactive_deletion "${files_to_delete[@]}" break ;; l|list|L|LIST) echo "Files to be deleted:" for file in "${files_to_delete[@]}"; do echo " - $(basename "$file")" done ;; *) echo "Invalid choice. Please enter y, n, i, or l." ;; esac done } # Function to delete files delete_files() { local files_to_delete=("$@") local deleted_count=0 local failed_count=0 echo "Deleting ${#files_to_delete[@]} files..." for file in "${files_to_delete[@]}"; do local filename=$(basename "$file") if rm -f "$file"; then log "INFO" "Deleted: $filename" echo " ✅ Deleted: $filename" ((deleted_count++)) else log "ERROR" "Failed to delete: $filename" echo " ❌ Failed to delete: $filename" ((failed_count++)) fi done echo "Deletion complete: $deleted_count deleted, $failed_count failed" } # Function for interactive deletion interactive_deletion() { local files_to_delete=("$@") local deleted_count=0 echo "Interactive deletion mode:" echo "For each file, choose: y=delete, n=keep, q=quit interactive mode" for file in "${files_to_delete[@]}"; do local filename=$(basename "$file") while true; do read -r -p "Delete '$filename'? [y/n/q]: " choice case "$choice" in y|Y) if rm -f "$file"; then log "INFO" "Deleted: $filename" echo " ✅ Deleted: $filename" ((deleted_count++)) else log "ERROR" "Failed to delete: $filename" echo " ❌ Failed to delete: $filename" fi break ;; n|N) echo " ⏭️ Keeping: $filename" break ;; q|Q) echo "Exiting interactive mode. Deleted $deleted_count files so far." return ;; *) echo "Invalid choice. Please enter y, n, or q." ;; esac done done echo "Interactive deletion complete: $deleted_count files deleted" } # Function to interactively handle corrupted files handle_corrupted_files() { local dry_run="$1" local files_deleted=0 if [[ ${#CORRUPTED_FILES[@]} -eq 0 ]]; then echo "✅ No corrupted archives found." return 0 fi echo "" echo "🔍 Found ${#CORRUPTED_FILES[@]} corrupted archive(s):" echo "" for file in "${CORRUPTED_FILES[@]}"; do local filename local file_size filename=$(basename "$file") file_size=$(stat -c%s "$file" 2>/dev/null || echo "unknown") echo " ❌ $filename (${file_size} bytes)" echo " Path: $file" if [[ "$dry_run" == "true" ]]; then echo " [DRY RUN] Would ask to delete this file" continue fi echo "" read -p "Delete this corrupted archive? [y/N]: " -r response case "$response" in [Yy]|[Yy][Ee][Ss]) if rm -f "$file"; then echo " ✅ Deleted: $filename" log "INFO" "Deleted corrupted archive: $file" ((files_deleted++)) else echo " ❌ Failed to delete: $filename" log "ERROR" "Failed to delete corrupted archive: $file" fi ;; *) echo " ⏭️ Skipped: $filename" ;; esac echo "" done if [[ "$dry_run" != "true" ]]; then echo "📊 Corrupted files processed: $files_deleted deleted, $((${#CORRUPTED_FILES[@]} - files_deleted)) kept" fi return $files_deleted } # Function to interactively handle collision files handle_collision_files() { local dry_run="$1" local files_deleted=0 local -A processed_groups if [[ ${#COLLISION_FILES[@]} -eq 0 ]]; then echo "✅ No case-collision duplicates found." return 0 fi echo "" echo "🔍 Found ${#COLLISION_FILES[@]} file(s) with case-collision issues:" echo "" # Group collision files by lowercase name local -A collision_groups for file in "${COLLISION_FILES[@]}"; do local filename local lowercase_name filename=$(basename "$file") lowercase_name="${filename,,}" if [[ -n "${collision_groups[$lowercase_name]:-}" ]]; then collision_groups["$lowercase_name"]+=$'\n'"$file" else collision_groups["$lowercase_name"]="$file" fi done # Process each collision group for lowercase_name in "${!collision_groups[@]}"; do local -a group_files mapfile -t group_files <<< "${collision_groups[$lowercase_name]}" if [[ ${#group_files[@]} -lt 2 ]]; then continue # Skip groups with less than 2 files fi echo "📁 Case collision group: '$lowercase_name'" # Display all files in the group with details for i in "${!group_files[@]}"; do local file="${group_files[$i]}" local filename local file_size local file_date filename=$(basename "$file") file_size=$(stat -c%s "$file" 2>/dev/null || echo "unknown") file_date=$(stat -c%y "$file" 2>/dev/null | cut -d' ' -f1 || echo "unknown") echo " $((i+1)). $filename" echo " Size: ${file_size} bytes, Date: $file_date" echo " Path: $file" done if [[ "$dry_run" == "true" ]]; then echo " [DRY RUN] Would ask which files to delete" echo "" continue fi echo "" echo "These files would conflict on case-insensitive filesystems (Windows/FAT32)." echo "Which files would you like to delete? (Enter numbers separated by spaces, or 'none')" read -p "Delete files [1-${#group_files[@]}] or 'none': " -r response case "$response" in [Nn][Oo][Nn][Ee]|"") echo " ⏭️ Skipped collision group: $lowercase_name" ;; *) # Parse the response and delete selected files for num in $response; do if [[ "$num" =~ ^[0-9]+$ && "$num" -ge 1 && "$num" -le ${#group_files[@]} ]]; then local file_to_delete="${group_files[$((num-1))]}" local filename_to_delete filename_to_delete=$(basename "$file_to_delete") if rm -f "$file_to_delete"; then echo " ✅ Deleted: $filename_to_delete" log "INFO" "Deleted collision file: $file_to_delete" ((files_deleted++)) else echo " ❌ Failed to delete: $filename_to_delete" log "ERROR" "Failed to delete collision file: $file_to_delete" fi else echo " ⚠️ Invalid selection: $num" fi done ;; esac echo "" done if [[ "$dry_run" != "true" ]]; then echo "📊 Collision files processed: $files_deleted deleted" fi return $files_deleted } # Function to display scan summary display_summary() { local input_dir="$1" local scan_only="$2" local total_files total_files=$(find "$input_dir" -maxdepth 1 -type f | wc -l) echo "" echo "📋 Scan Summary" echo "════════════════════════════════════════════════════════════════" echo " 📁 Directory scanned: $input_dir" echo " 📄 Total files found: $total_files" echo " 🧪 Archives tested for corruption: $CORRUPTION_TESTS" echo " 🔍 Files checked for collisions: $COLLISION_CHECKS" echo "" echo " ❌ Corrupted archives: ${#CORRUPTED_FILES[@]}" echo " 🔄 Case-collision files: ${#COLLISION_FILES[@]}" echo "" if [[ "$scan_only" == "true" ]]; then echo "ℹ️ Scan completed. Use --remove-corrupted and/or --fix-collisions to fix issues." else echo "✅ Archive scan and cleanup completed successfully." fi log "INFO" "Archive scan completed successfully" log "INFO" "Summary: $total_files total files, $CORRUPTION_TESTS tested, ${#CORRUPTED_FILES[@]} corrupted, ${#COLLISION_FILES[@]} collisions" } # Main script execution main() { local input_dir="" local scan_only=true # Parse arguments while [[ $# -gt 0 ]]; do case $1 in --fix-collisions) FIX_COLLISIONS=true scan_only=false shift ;; --remove-corrupted) REMOVE_CORRUPTED=true scan_only=false shift ;; --parallel) if [[ -n "$2" && "$2" =~ ^[1-8]$ ]]; then MAX_PARALLEL_JOBS="$2" shift 2 else log "ERROR" "Invalid parallel jobs count. Must be 1-8." exit 1 fi ;; --dry-run) DRY_RUN=true shift ;; --verbose) VERBOSE=true LOG_LEVEL="DEBUG" shift ;; -h|--help) show_usage exit 0 ;; -*) log "ERROR" "Unknown option: $1" show_usage exit 1 ;; *) if [[ -z "$input_dir" ]]; then input_dir="$1" else log "ERROR" "Multiple directories specified: $input_dir and $1" show_usage exit 1 fi shift ;; esac done # Validate required parameters if [[ -z "$input_dir" ]]; then log "ERROR" "No directory specified" show_usage exit 1 fi log "INFO" "Starting archive scan with parallel jobs: $MAX_PARALLEL_JOBS" log "INFO" "Options: fix_collisions=$FIX_COLLISIONS, remove_corrupted=$REMOVE_CORRUPTED, dry_run=$DRY_RUN" # Validate input and dependencies validate_input "$input_dir" check_dependencies # Perform scans echo "🔍 Scanning archives in: $input_dir" echo "⚙️ Using $MAX_PARALLEL_JOBS parallel jobs for corruption testing" echo "" scan_corrupted_archives "$input_dir" scan_filename_collisions "$input_dir" # Handle issues if requested local total_deleted=0 if [[ "$REMOVE_CORRUPTED" == "true" ]]; then handle_corrupted_files "$DRY_RUN" total_deleted=$((total_deleted + $?)) fi if [[ "$FIX_COLLISIONS" == "true" ]]; then handle_collision_files "$DRY_RUN" total_deleted=$((total_deleted + $?)) fi # Display summary display_summary "$input_dir" "$scan_only" if [[ $total_deleted -gt 0 && "$DRY_RUN" != "true" ]]; then echo "🗑️ Total files deleted: $total_deleted" log "INFO" "Total files deleted: $total_deleted" fi } # Show usage if no arguments provided if [[ $# -eq 0 ]]; then show_usage exit 1 fi # Run the main function with all arguments main "$@"