#!/bin/bash ################################################################################ # Script: sort2folders.sh # Description: Organizes ROM files into alphabetical subdirectories for easier # navigation on flashcarts and low-power systems. Moves files # (non-recursively) into subfolders based on the first character # of the filename. # # Usage: ./sort2folders.sh [max_files_per_group] # # Dependencies: # - config.sh # - logger.sh # # Organization Strategy: # - Smart grouping: combines letters when file count is manageable # - Default max files per group: 50 (ideal for flashcart navigation) # - Creates ranges like #-B/, C-E/, F/, etc. based on actual file distribution # - Numbers/symbols (represented by #) are treated as alphabetically first # - Sub-letter splitting for massive collections (S#-Sg/, Sh-So/, etc.) # - Numbers/symbols handled intelligently and represented with # symbol # - Compatible with FAT32 (no problematic characters) # - Overwrites files if they already exist in destination # # Examples: # ./sort2folders.sh /data/emu/org/nes.usa.1g1r/ # ./sort2folders.sh /data/emu/org/nes.usa.1g1r/ 50 ################################################################################ # Script identification SCRIPT_NAME="sort2folders.sh" # Global variables for smart grouping declare -a GROUPING_STRATEGY # Global dry-run flag DRY_RUN=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 core 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 [max_files_per_group] [--dry-run]" echo "" echo "Organizes ROM files into smart alphabetical subdirectories for flashcart navigation." echo "" echo "Parameters:" echo " Path to directory containing ROM files to organize" echo " [max_files_per_group] Maximum files per group (default: 50)" echo " [--dry-run] Preview operations without making changes" echo "" echo "Smart Organization:" echo " - Analyzes file distribution across #,A-Z and creates optimal groups" echo " - Numbers/symbols (#) are treated as alphabetically first" echo " - Combines letters when total ≤ max_files_per_group" echo " - Creates ranges like #-B/, C-E/, F/, G-M/, etc." echo " - Sub-letter splitting for massive collections (S#-Sg/, Sh-So/, etc.)" echo " - Numbers/symbols grouped intelligently and represented with # symbol" echo "" echo "Examples:" echo " $0 /data/emu/org/nes.usa.1g1r/ # Use default 50 files per group" echo " $0 /data/emu/org/snes.usa.1g1r/ 50 # Use 50 files per group" echo " $0 /path/to/flashcart/roms/ 30 # Use 30 files per group" echo " $0 /path/to/roms/ 50 --dry-run # Preview changes without moving files" echo "" echo "Note: Files are moved (not copied) and will overwrite existing files unless --dry-run is used." } # Function to validate input directory validate_input() { local input_dir="$1" if [[ -z "$input_dir" ]]; then log "ERROR" "No directory specified" show_usage exit 1 fi 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 [[ ! -w "$input_dir" ]]; then log "ERROR" "Directory is not writable: $input_dir" exit 1 fi log "INFO" "Input directory validated: $input_dir" } # Function to count files to be organized count_files() { local input_dir="$1" local file_count file_count=$(find "$input_dir" -maxdepth 1 -type f | wc -l) if [[ $file_count -eq 0 ]]; then log "WARN" "No files found in directory: $input_dir" echo "No files to organize in the specified directory." exit 0 fi log "INFO" "Found $file_count files to organize" echo "Found $file_count files to organize into smart alphabetical subdirectories." return $file_count } # Function to analyze file distribution by first character analyze_file_distribution() { local input_dir="$1" local -A char_counts local total_files=0 log "INFO" "Analyzing file distribution by first character" # Count files by first character while IFS= read -r file; do local filename local first_char local first_char_upper filename=$(basename "$file") first_char="${filename:0:1}" first_char_upper=$(echo "$first_char" | tr '[:lower:]' '[:upper:]') if [[ "$first_char_upper" =~ [A-Z] ]]; then ((char_counts["$first_char_upper"]++)) else ((char_counts["#"]++)) # Numbers and symbols now use # instead of 0-9# fi ((total_files++)) done < <(find "$input_dir" -maxdepth 1 -type f) log "DEBUG" "File distribution analysis complete: $total_files total files" # Output the associative array in a way that can be read by caller # Note: # comes first alphabetically now for char in "#" {A..Z}; do echo "$char:${char_counts[$char]:-0}" done } # Function to analyze sub-letter distribution for massive single-letter groups analyze_subletter_distribution() { local input_dir="$1" local target_char="$2" local -A subletter_counts local total_files=0 log "INFO" "Analyzing sub-letter distribution for $target_char files" # Count files by second character for the target letter while IFS= read -r file; do local filename local first_char local second_char local first_char_upper local second_char_upper filename=$(basename "$file") first_char="${filename:0:1}" first_char_upper=$(echo "$first_char" | tr '[:lower:]' '[:upper:]') # Check if this file matches the target character local matches_target=false if [[ "$target_char" == "#" ]]; then # For # target, match files that start with non-letters if [[ ! "$first_char_upper" =~ [A-Z] ]]; then matches_target=true fi else # For letter targets, match exact character if [[ "$first_char_upper" == "$target_char" ]]; then matches_target=true fi fi if [[ "$matches_target" == true ]]; then second_char="${filename:1:1}" second_char_upper=$(echo "$second_char" | tr '[:lower:]' '[:upper:]') if [[ "$second_char_upper" =~ [A-Z] ]]; then ((subletter_counts["$second_char_upper"]++)) else ((subletter_counts["#"]++)) # Non-letters fi ((total_files++)) fi done < <(find "$input_dir" -maxdepth 1 -type f) log "DEBUG" "Sub-letter analysis complete for $target_char: $total_files total files" # Output the associative array for char in "#" {A..Z}; do if [[ ${subletter_counts[$char]:-0} -gt 0 ]]; then echo "$target_char$char:${subletter_counts[$char]}" fi done } # Function to create sub-letter grouping strategy for massive single letters create_subletter_strategy() { local target_char="$1" local max_files="$2" local input_dir="$3" local -A subletter_counts local -a subgroups local current_start="" local current_end="" local current_count=0 log "INFO" "Creating sub-letter grouping strategy for $target_char with max $max_files files per group" # Get sub-letter distribution while IFS=':' read -r subletter count; do local second_char="${subletter:1:1}" subletter_counts["$second_char"]=$count done < <(analyze_subletter_distribution "$input_dir" "$target_char") # Process # and A-Z for second characters (# comes first now) for char in "#" {A..Z}; do local count=${subletter_counts[$char]:-0} if [[ $count -eq 0 ]]; then continue # Skip characters with no files fi # Check if adding this character would exceed max if [[ $((current_count + count)) -gt $max_files && -n "$current_start" ]]; then # Finish current group if [[ "$current_start" == "$current_end" ]]; then subgroups+=("$target_char$current_start:$current_count") log "DEBUG" "Sub-letter single char group: $target_char$current_start ($current_count files)" else subgroups+=("$target_char$current_start-$target_char$current_end:$current_count") log "DEBUG" "Sub-letter range group: $target_char$current_start-$target_char$current_end ($current_count files)" fi current_start="$char" current_end="$char" current_count=$count else # Add to current group if [[ -z "$current_start" ]]; then current_start="$char" fi current_end="$char" current_count=$((current_count + count)) fi done # Finish the last group if it exists if [[ -n "$current_start" ]]; then if [[ "$current_start" == "$current_end" ]]; then subgroups+=("$target_char$current_start:$current_count") log "DEBUG" "Final sub-letter single char group: $target_char$current_start ($current_count files)" else subgroups+=("$target_char$current_start-$target_char$current_end:$current_count") log "DEBUG" "Final sub-letter range group: $target_char$current_start-$target_char$current_end ($current_count files)" fi fi # Process subgroups with proper range logic local -a simplified_subgroups # If there's only one sub-letter group, simplify it to just the letter if [[ ${#subgroups[@]} -eq 1 ]]; then local total_count=0 for subgroup in "${subgroups[@]}"; do IFS=':' read -r group_name group_count <<< "$subgroup" total_count=$((total_count + group_count)) done simplified_subgroups+=("$target_char:$total_count") log "DEBUG" "Simplified single sub-letter group: $target_char ($total_count files)" else # Multiple groups - process each with proper range logic for i in "${!subgroups[@]}"; do IFS=':' read -r group_name group_count <<< "${subgroups[$i]}" if [[ "$group_name" =~ ^[A-Z#][A-Z#]-[A-Z#][A-Z#]$ || "$group_name" =~ ^[#][A-Z#]-[#][A-Z#]$ ]]; then local start_first="${group_name:0:1}" local start_second="${group_name:1:1}" local end_first="${group_name:3:1}" local end_second="${group_name:4:1}" # If this is the last sub-letter group, extend to Z for clarity if [[ $i -eq $((${#subgroups[@]} - 1)) ]]; then simplified_subgroups+=("$start_first$start_second-${start_first}Z:$group_count") log "DEBUG" "Final sub-letter range extended to Z: $start_first$start_second-${start_first}Z ($group_count files)" else # Keep the original range for non-final groups simplified_subgroups+=("$group_name:$group_count") log "DEBUG" "Sub-letter range kept as-is: $group_name ($group_count files)" fi elif [[ "$group_name" =~ ^[A-Z#][A-Z#]$ ]]; then # Single sub-letter groups need to be handled specially if [[ $i -eq $((${#subgroups[@]} - 1)) ]]; then # Last group - extend to Z simplified_subgroups+=("$group_name-${target_char}Z:$group_count") log "DEBUG" "Final single sub-letter extended to Z: $group_name-${target_char}Z ($group_count files)" else # Non-final single groups stay as-is simplified_subgroups+=("$group_name:$group_count") log "DEBUG" "Single sub-letter group: $group_name ($group_count files)" fi else # Other format simplified_subgroups+=("$group_name:$group_count") log "DEBUG" "Sub-letter group: $group_name ($group_count files)" fi done fi # Handle non-letter second characters - only create separate group if not already handled local nonletter_count=${subletter_counts["#"]:-0} local already_handled=false # Check if # was already included in the main grouping for subgroup in "${simplified_subgroups[@]}"; do IFS=':' read -r group_name group_count <<< "$subgroup" if [[ "$group_name" == *"#"* ]]; then already_handled=true break fi done if [[ $nonletter_count -gt 0 && "$already_handled" == false ]]; then simplified_subgroups+=("$target_char#:$nonletter_count") log "DEBUG" "Sub-letter non-letter group: $target_char# ($nonletter_count files)" fi # Output the simplified sub-groups for subgroup in "${simplified_subgroups[@]}"; do echo "$subgroup" done log "INFO" "Created ${#subgroups[@]} sub-letter groups for $target_char" } # Function to create smart grouping strategy create_grouping_strategy() { local max_files="$1" local input_dir="$2" local -A char_counts local -a groups local current_start="" local current_end="" local current_count=0 log "INFO" "Creating smart grouping strategy with max $max_files files per group" # Read character counts from stdin while IFS=':' read -r char count; do char_counts["$char"]=$count done # Process # and A-Z first (# comes before letters alphabetically) for char in "#" {A..Z}; do local count=${char_counts[$char]:-0} if [[ $count -eq 0 ]]; then continue # Skip characters with no files fi # If this character alone exceeds max, check if it needs sub-letter splitting if [[ $count -gt $max_files ]]; then # Finish current group if it exists if [[ -n "$current_start" ]]; then if [[ "$current_start" == "$current_end" ]]; then groups+=("$current_start:$current_count") log "DEBUG" "Single char group: $current_start ($current_count files)" else groups+=("$current_start-$current_end:$current_count") log "DEBUG" "Range group: $current_start-$current_end ($current_count files)" fi current_start="" current_end="" current_count=0 fi # Check if this massive group needs sub-letter splitting local subletter_threshold=$((max_files * 3)) # Trigger at 3x max_files if [[ $count -ge $subletter_threshold ]]; then log "INFO" "Character $char has $count files (>= $subletter_threshold threshold) - applying sub-letter splitting" # Create sub-letter groups for this massive character while IFS=':' read -r subgroup_name subgroup_count; do groups+=("$subgroup_name:$subgroup_count") log "DEBUG" "Sub-letter group: $subgroup_name ($subgroup_count files)" done < <(create_subletter_strategy "$char" "$max_files" "$input_dir") else # Add this character as its own group (large but not massive) groups+=("$char:$count") log "DEBUG" "Large group: $char ($count files) - exceeds max, gets own directory" fi continue fi # Check if adding this character would exceed max if [[ $((current_count + count)) -gt $max_files && -n "$current_start" ]]; then # Finish current group if [[ "$current_start" == "$current_end" ]]; then groups+=("$current_start:$current_count") log "DEBUG" "Single char group: $current_start ($current_count files)" else groups+=("$current_start-$current_end:$current_count") log "DEBUG" "Range group: $current_start-$current_end ($current_count files)" fi current_start="$char" current_end="$char" current_count=$count else # Add to current group if [[ -z "$current_start" ]]; then current_start="$char" fi current_end="$char" current_count=$((current_count + count)) fi done # Finish the last group if it exists if [[ -n "$current_start" ]]; then if [[ "$current_start" == "$current_end" ]]; then groups+=("$current_start:$current_count") log "DEBUG" "Final single char group: $current_start ($current_count files)" else groups+=("$current_start-$current_end:$current_count") log "DEBUG" "Final range group: $current_start-$current_end ($current_count files)" fi fi # Output the groups for group in "${groups[@]}"; do echo "$group" done log "INFO" "Created ${#groups[@]} smart groups" } # Function to determine target directory for a file using grouping strategy get_target_directory_smart() { local filename="$1" local input_dir="$2" local first_char="${filename:0:1}" local second_char="${filename:1:1}" local first_char_upper local second_char_upper first_char_upper=$(echo "$first_char" | tr '[:lower:]' '[:upper:]') second_char_upper=$(echo "$second_char" | tr '[:lower:]' '[:upper:]') # Normalize non-letters to # for consistent matching if [[ ! "$first_char_upper" =~ [A-Z] ]]; then first_char_upper="#" fi # Read grouping strategy from global variable for group_info in "${GROUPING_STRATEGY[@]}"; do IFS=':' read -r group_name group_count <<< "$group_info" # Handle sub-letter groups (e.g., SA-SG, SH-SZ, S#-SZ) if [[ "$group_name" =~ ^[A-Z#][A-Z#]-[A-Z#][A-Z#]$ ]]; then local start_first="${group_name:0:1}" local start_second="${group_name:1:1}" local end_first="${group_name:3:1}" local end_second="${group_name:4:1}" # Check if file matches this sub-letter range if [[ "$first_char_upper" == "$start_first" && "$first_char_upper" == "$end_first" ]]; then # Same first character - check second character range local file_second_char="$second_char_upper" if [[ ! "$second_char_upper" =~ [A-Z] ]]; then file_second_char="#" # Non-letters become # fi # Check if file's second character is in range (# comes before A-Z) if [[ "$start_second" == "#" && "$end_second" =~ [A-Z] ]]; then # Range from # to letter (e.g., S#-SG) if [[ "$file_second_char" == "#" ]] || [[ "$file_second_char" =~ [A-Z] && ( "$file_second_char" < "$end_second" || "$file_second_char" == "$end_second" ) ]]; then echo "$input_dir/$group_name" return fi elif [[ "$start_second" =~ [A-Z] && "$end_second" =~ [A-Z] ]]; then # Range from letter to letter (e.g., SA-SG) if [[ "$file_second_char" =~ [A-Z] && ( "$file_second_char" > "$start_second" || "$file_second_char" == "$start_second" ) && ( "$file_second_char" < "$end_second" || "$file_second_char" == "$end_second" ) ]]; then echo "$input_dir/$group_name" return fi fi fi fi # Handle sub-letter groups ending in Z (e.g., SA-SZ, SH-SZ, S#-SZ) if [[ "$group_name" =~ ^[A-Z#][A-Z#]-[A-Z#]Z$ ]]; then local start_first="${group_name:0:1}" local start_second="${group_name:1:1}" local end_first="${group_name:3:1}" # Check if file matches this sub-letter range if [[ "$first_char_upper" == "$start_first" && "$first_char_upper" == "$end_first" ]]; then # Same first character - check second character range (start to Z) local file_second_char="$second_char_upper" if [[ ! "$second_char_upper" =~ [A-Z] ]]; then file_second_char="#" # Non-letters become # fi if [[ "$start_second" == "#" ]]; then # Range from # to Z (e.g., S#-SZ) - includes everything echo "$input_dir/$group_name" return elif [[ "$start_second" =~ [A-Z] ]]; then # Range from letter to Z (e.g., SH-SZ) if [[ "$file_second_char" =~ [A-Z] && ( "$file_second_char" > "$start_second" || "$file_second_char" == "$start_second" ) ]]; then echo "$input_dir/$group_name" return fi fi fi fi # Handle single sub-letter groups (e.g., SA, SB, S#) if [[ "$group_name" =~ ^[A-Z#][A-Z#]$ ]]; then local target_first="${group_name:0:1}" local target_second="${group_name:1:1}" if [[ "$first_char_upper" == "$target_first" ]]; then local file_second_char="$second_char_upper" if [[ ! "$second_char_upper" =~ [A-Z] ]]; then file_second_char="#" # Non-letters become # fi if [[ "$file_second_char" == "$target_second" ]]; then echo "$input_dir/$group_name" return fi fi fi # Handle symbols group (files starting with numbers/symbols) if [[ "$group_name" == "#" && "$first_char_upper" == "#" ]]; then echo "$input_dir/#" return fi # Handle regular groups (including # ranges) if [[ "$group_name" == *"-"* && ! "$group_name" =~ ^[A-Z#][A-Z#]-[A-Z#][A-Z#]$ && ! "$group_name" =~ ^[A-Z#][A-Z#]-[A-Z#]Z$ ]]; then # Range group (e.g., A-C, #-B) local start_char="${group_name%-*}" local end_char="${group_name#*-}" # Use the already normalized first character local file_first_char="$first_char_upper" # Check if file is in range if [[ "$start_char" == "#" ]]; then # Range starting with # (e.g., #-C) if [[ "$file_first_char" == "#" ]] || [[ "$file_first_char" =~ [A-Z] && ( "$file_first_char" < "$end_char" || "$file_first_char" == "$end_char" ) ]]; then echo "$input_dir/$group_name" return fi else # Normal alphabetic range (e.g., A-C) if [[ "$file_first_char" =~ [A-Z] ]] && [[ "$file_first_char" > "$start_char" || "$file_first_char" == "$start_char" ]] && [[ "$file_first_char" < "$end_char" || "$file_first_char" == "$end_char" ]]; then echo "$input_dir/$group_name" return fi fi elif [[ "$group_name" == "#" && ! "$first_char_upper" =~ [A-Z] ]]; then # Single # group for numbers/symbols echo "$input_dir/#" return elif [[ "$group_name" == "$first_char_upper" && ${#group_name} -eq 1 && "$first_char_upper" =~ [A-Z] ]]; then # Single character group (A, B, C, etc.) - only for letters echo "$input_dir/$group_name" return fi done # Fallback (shouldn't happen with normal files) local file_first_char="$first_char_upper" # Already normalized # Log warnings to stderr to avoid contaminating the return value { log "WARN" "No group found for file: $filename" log "WARN" " - First character: '$first_char' (normalized: '$file_first_char')" log "WARN" " - Second character: '$second_char' (normalized: '$second_char_upper')" log "WARN" " - Available groups: ${#GROUPING_STRATEGY[@]} total" log "WARN" " - Moving to 'Other' directory for manual review" } >&2 echo "$input_dir/Other" } # Function to organize files into subdirectories organize_files() { local input_dir="$1" local files_processed=0 local files_failed=0 local directories_created=0 local -A dir_counts if [[ "$DRY_RUN" == true ]]; then log "INFO" "DRY RUN: Previewing file organization using smart grouping strategy (no files will be moved)" else log "INFO" "Starting file organization process using smart grouping strategy" fi # Process each file in the directory (non-recursive) while IFS= read -r file; do local filename local target_dir local first_char_display filename=$(basename "$file") target_dir=$(get_target_directory_smart "$filename" "$input_dir") first_char_display=$(basename "$target_dir") # Create target directory if it doesn't exist (or preview in dry-run) if [[ ! -d "$target_dir" ]]; then if [[ "$DRY_RUN" == true ]]; then log "DEBUG" "DRY RUN: Would create directory: $target_dir" ((directories_created++)) # Log a warning if this would be the fallback "Other" directory if [[ "$(basename "$target_dir")" == "Other" ]]; then log "WARN" "DRY RUN: Would create fallback 'Other' directory for problematic files: $target_dir" fi else if mkdir -p "$target_dir"; then log "DEBUG" "Created directory: $target_dir" ((directories_created++)) # Log a warning if this is the fallback "Other" directory if [[ "$(basename "$target_dir")" == "Other" ]]; then log "WARN" "Created fallback 'Other' directory for problematic files: $target_dir" fi else log "ERROR" "Failed to create directory: $target_dir" ((files_failed++)) continue fi fi fi # Move the file (overwrite if exists) or preview in dry-run if [[ "$DRY_RUN" == true ]]; then if [[ "$(basename "$target_dir")" == "Other" ]]; then log "WARN" "DRY RUN: Would move problematic file to Other directory: $filename → Other/" else log "DEBUG" "DRY RUN: Would move: $filename → $first_char_display/" fi ((files_processed++)) ((dir_counts["$first_char_display"]++)) else if mv "$file" "$target_dir/"; then if [[ "$(basename "$target_dir")" == "Other" ]]; then log "WARN" "Moved problematic file to Other directory: $filename → Other/" else log "DEBUG" "Moved: $filename → $first_char_display/" fi ((files_processed++)) ((dir_counts["$first_char_display"]++)) else log "ERROR" "Failed to move file '$filename' to '$target_dir/'. File may have invalid characters or permissions issues." ((files_failed++)) fi fi done < <(find "$input_dir" -maxdepth 1 -type f) # Log summary statistics if [[ "$DRY_RUN" == true ]]; then log "INFO" "DRY RUN: Preview completed: $files_processed files would be processed, $files_failed would fail" log "INFO" "DRY RUN: Would create $directories_created new directories" else log "INFO" "Organization completed: $files_processed files processed, $files_failed failed" log "INFO" "Created $directories_created new directories" fi # Display results echo "" if [[ "$DRY_RUN" == true ]]; then echo "DRY RUN - Preview Results (no changes made):" echo " Files that would be processed: $files_processed" echo " Files that would fail: $files_failed" echo " Directories that would be created: $directories_created" else echo "Organization Results:" echo " Files processed: $files_processed" echo " Files failed: $files_failed" echo " Directories created: $directories_created" fi echo "" if [[ ${#dir_counts[@]} -gt 0 ]]; then if [[ "$DRY_RUN" == true ]]; then echo "Files per directory (preview):" else echo "Files per directory:" fi for dir in $(printf '%s\n' "${!dir_counts[@]}" | sort); do echo " $dir/: ${dir_counts[$dir]} files" done fi return $files_failed } # Function to display a summary display_summary() { local input_dir="$1" local max_files="$2" local total_dirs if [[ "$DRY_RUN" == true ]]; then # In dry-run mode, don't count actual directories that might be created total_dirs="N/A (dry run)" log "INFO" "DRY RUN: Preview completed successfully" log "INFO" "DRY RUN Summary:" log "INFO" " - Input directory: $input_dir" log "INFO" " - Subdirectories that would be created: See preview above" log "INFO" " - Max files per group: $max_files" log "INFO" " - Organization strategy: Smart alphabetical grouping" echo "" echo "🔍 DRY RUN: Preview completed - ROM files would be organized into smart alphabetical subdirectories." echo "📁 Directory structure would be optimized for flashcart navigation with max $max_files files per group." echo "💡 To perform the actual organization, run the same command without --dry-run" else total_dirs=$(find "$input_dir" -maxdepth 1 -type d | grep -v "^$input_dir$" | wc -l) log "INFO" "Organization completed successfully" log "INFO" "Summary:" log "INFO" " - Input directory: $input_dir" log "INFO" " - Total subdirectories: $total_dirs" log "INFO" " - Max files per group: $max_files" log "INFO" " - Organization strategy: Smart alphabetical grouping" echo "" echo "✅ ROM files have been organized into smart alphabetical subdirectories." echo "📁 Directory structure optimized for flashcart navigation with max $max_files files per group." fi } # Main script execution main() { local input_dir="" local max_files_per_group="50" # Default to 50 files per group # Parse arguments while [[ $# -gt 0 ]]; do case $1 in --dry-run) DRY_RUN=true shift ;; --help|-h) show_usage exit 0 ;; *) if [[ -z "$input_dir" ]]; then input_dir="$1" elif [[ "$1" =~ ^[1-9][0-9]*$ ]]; then max_files_per_group="$1" else log "ERROR" "Invalid argument: $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 # Validate max_files_per_group is a positive integer if [[ ! "$max_files_per_group" =~ ^[1-9][0-9]*$ ]]; then log "ERROR" "Invalid max_files_per_group: $max_files_per_group (must be positive integer)" show_usage exit 1 fi if [[ "$DRY_RUN" == true ]]; then log "INFO" "DRY RUN MODE: Using smart grouping with max $max_files_per_group files per group (preview only)" else log "INFO" "Using smart grouping with max $max_files_per_group files per group" fi # Validate input validate_input "$input_dir" # Count files and confirm operation count_files "$input_dir" # Analyze file distribution and create grouping strategy log "INFO" "Analyzing file distribution to create optimal grouping strategy" mapfile -t distribution < <(analyze_file_distribution "$input_dir") # Create grouping strategy (suppress log output during creation) LOG_LEVEL_BACKUP="$LOG_LEVEL" LOG_LEVEL="ERROR" # Only show ERROR logs during strategy creation mapfile -t GROUPING_STRATEGY < <(printf '%s\n' "${distribution[@]}" | create_grouping_strategy "$max_files_per_group" "$input_dir") LOG_LEVEL="$LOG_LEVEL_BACKUP" # Display grouping strategy echo "" if [[ "$DRY_RUN" == true ]]; then echo "Smart Grouping Strategy (DRY RUN - Preview Only):" else echo "Smart Grouping Strategy:" fi for group_info in "${GROUPING_STRATEGY[@]}"; do IFS=':' read -r group_name group_count <<< "$group_info" echo " $group_name/: $group_count files" done echo "" # Organize files if organize_files "$input_dir"; then display_summary "$input_dir" "$max_files_per_group" else if [[ "$DRY_RUN" == true ]]; then log "ERROR" "DRY RUN: Preview completed with potential errors" else log "ERROR" "Organization completed with errors" fi exit 1 fi } # Show usage if no arguments provided if [[ $# -eq 0 ]]; then show_usage exit 1 fi # Run the main function with all arguments main "$@"