#!/bin/bash ################################################################################ # Script: organize-roms.sh # Description: Organizes ROMs into subdirectories based on region and kind (physical), # and creates language symlinks (virtual). # # Usage: ./organize-roms.sh [--dry-run] # # Dependencies: # - utils.sh for shared utility functions. # - logger.sh for consistent and color-coded logging. # - config-arrays.sh for dynamic array definitions. ################################################################################ # Global dry-run flag DRY_RUN=false # Configuration: # # PHYSICAL ORGANIZATION (moves files): # KEEP_IN_ROOT_REGIONS - Regions to keep in root (e.g., "USA,World") # KEEP_IN_ROOT_KINDS - Kinds to keep in place (e.g., "Demo,Beta") # # VIRTUAL ORGANIZATION (creates symlinks): # ORGANIZE_LANGUAGES_BY_SYMLINK - Enable language symlinks (true/false) # LANGUAGE_EXCLUDE_REGIONS - Don't create language symlinks for these regions # # Variable behavior: # NOT SET: Don't organize that type # EMPTY (""): Organize everything # WITH VALUES: Keep/exclude those values # Determine the directory of the current script SCRIPT_DIR="$(dirname "$(realpath "$0")")" # Determine the project root directory PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" # Load shared libraries source "${PROJECT_ROOT}/core/config.sh" source "${PROJECT_ROOT}/core/logger.sh" source "${PROJECT_ROOT}/core/utils.sh" source "${PROJECT_ROOT}/core/config-arrays.sh" # Log the script name when it is called log "DEBUG" "Starting script: $(basename "$0")" # Function to display usage display_usage() { log "INFO" "Usage: $0 [--dry-run]" log "INFO" "" log "INFO" "Description:" log "INFO" " Organizes ROMs into subdirectories." log "INFO" " - Physical: Regions and kinds (moves files)" log "INFO" " - Virtual: Languages (creates symlinks)" log "INFO" "" log "INFO" "Environment Variables (Physical Organization):" log "INFO" " KEEP_IN_ROOT_REGIONS - Regions to keep in root (e.g., 'USA,World')" log "INFO" " Not set = no region organization" log "INFO" " Empty = organize all regions" log "INFO" " With values = keep those in root" log "INFO" "" log "INFO" " KEEP_IN_ROOT_KINDS - Kinds to keep in place (e.g., 'Demo,Beta')" log "INFO" " Not set = no kind organization" log "INFO" " Empty = organize all kinds recursively" log "INFO" " With values = keep those in place" log "INFO" "" log "INFO" "Environment Variables (Virtual Organization - Symlinks):" log "INFO" " ORGANIZE_LANGUAGES_BY_SYMLINK - Enable language symlinks (true/false)" log "INFO" " Creates 'By Language//' folders" log "INFO" " with symlinks to ROMs wherever they are" log "INFO" "" log "INFO" " LANGUAGE_EXCLUDE_REGIONS - Don't create language symlinks for these regions" log "INFO" " (e.g., 'USA,World' - USA games are always English)" log "INFO" "" log "INFO" "Options:" log "INFO" " --dry-run Preview changes without moving files or creating symlinks." log "INFO" "" log "INFO" "Examples:" log "INFO" " # USA Build: Keep USA/World in root, organize kinds, no language folders" log "INFO" " export KEEP_IN_ROOT_REGIONS='USA,World'" log "INFO" " export KEEP_IN_ROOT_KINDS=''" log "INFO" " export ORGANIZE_LANGUAGES_BY_SYMLINK='false'" log "INFO" " $0 /path/to/roms" log "INFO" "" log "INFO" " # English Build: Keep USA in root, create language symlinks for foreign games" log "INFO" " export KEEP_IN_ROOT_REGIONS='USA,World'" log "INFO" " export KEEP_IN_ROOT_KINDS=''" log "INFO" " export ORGANIZE_LANGUAGES_BY_SYMLINK='true'" log "INFO" " export LANGUAGE_EXCLUDE_REGIONS='USA,World'" log "INFO" " $0 /path/to/roms" log "INFO" "" log "INFO" " # All Regions Build: Organize everything, symlink all languages" log "INFO" " export KEEP_IN_ROOT_REGIONS=''" log "INFO" " export ORGANIZE_LANGUAGES_BY_SYMLINK='true'" log "INFO" " export LANGUAGE_EXCLUDE_REGIONS=''" log "INFO" " $0 /path/to/roms" # Only exit if script is executed directly, not sourced if [[ "${BASH_SOURCE[1]}" != "${0}" ]]; then return 1 else exit 1 fi } ################################################################################ # Validation function - validates KEEP_IN_ROOT_* and language variables ################################################################################ validate_keep_in_root_settings() { local valid=true # Validate regions if [[ -v KEEP_IN_ROOT_REGIONS && -n "$KEEP_IN_ROOT_REGIONS" ]]; then log "DEBUG" "Validating KEEP_IN_ROOT_REGIONS: $KEEP_IN_ROOT_REGIONS" IFS=',' read -ra regions <<< "$KEEP_IN_ROOT_REGIONS" for region in "${regions[@]}"; do # Trim whitespace region="${region// /}" # Check if region exists in REGION_ARRAY if [[ ! " ${REGION_ARRAY[*]} " =~ " ${region} " ]]; then log "WARN" "Unknown region in KEEP_IN_ROOT_REGIONS: '$region'" log "WARN" "Valid regions: ${REGION_ARRAY[*]}" valid=false fi done fi # Validate language exclude regions if [[ -v LANGUAGE_EXCLUDE_REGIONS && -n "$LANGUAGE_EXCLUDE_REGIONS" ]]; then log "DEBUG" "Validating LANGUAGE_EXCLUDE_REGIONS: $LANGUAGE_EXCLUDE_REGIONS" IFS=',' read -ra regions <<< "$LANGUAGE_EXCLUDE_REGIONS" for region in "${regions[@]}"; do region="${region// /}" if [[ ! " ${REGION_ARRAY[*]} " =~ " ${region} " ]]; then log "WARN" "Unknown region in LANGUAGE_EXCLUDE_REGIONS: '$region'" log "WARN" "Valid regions: ${REGION_ARRAY[*]}" valid=false fi done fi # Validate kinds if [[ -v KEEP_IN_ROOT_KINDS && -n "$KEEP_IN_ROOT_KINDS" ]]; then log "DEBUG" "Validating KEEP_IN_ROOT_KINDS: $KEEP_IN_ROOT_KINDS" IFS=',' read -ra kinds <<< "$KEEP_IN_ROOT_KINDS" for kind in "${kinds[@]}"; do kind="${kind// /}" if [[ ! -v GLOBAL_KINDS["$kind"] ]]; then log "WARN" "Unknown kind in KEEP_IN_ROOT_KINDS: '$kind'" log "WARN" "Valid kinds: ${!GLOBAL_KINDS[*]}" valid=false fi done fi if [[ "$valid" == "false" ]]; then log "ERROR" "Invalid KEEP_IN_ROOT settings detected. Please fix and try again." return 1 fi return 0 } # Function to organize ROMs by language organize_language() { local inFolder=$1 local language=$2 log "INFO" "Organizing ROMs by language: $language" # Define language directory (created on-demand) local langDir="${inFolder}/By Language/${language}" local file_count=0 # Move ROMs matching the language pattern find "$inFolder" -type f -name "*[(,]$language[),]*" ! -name "*.m3u" -print0 | while IFS= read -r -d '' file; do # Create language directory only when first file is found if [[ ! -d "$langDir" ]]; then create_directory "$langDir" log "INFO" "Created language directory: $language" fi move_with_playlist "$file" "$langDir" ((file_count++)) done # Only log if files were found if [[ $file_count -gt 0 ]]; then log "INFO" "Organized $file_count ROM(s) for language: $language" fi } # Function to organize ROMs by region organize_region() { local inFolder=$1 local region=$2 log "INFO" "Organizing ROMs by region: $region" # Define region directory (created on-demand) local regionDir="${inFolder}/By Region/${region}" local file_count=0 # Move ROMs matching the region pattern find "$inFolder" -type f -name "*[(,]$region[),]*" ! -name "*.m3u" -print0 | while IFS= read -r -d '' file; do # Create region directory only when first file is found if [[ ! -d "$regionDir" ]]; then create_directory "$regionDir" log "INFO" "Created region directory: $region" fi move_with_playlist "$file" "$regionDir" ((file_count++)) done # Only log if files were found if [[ $file_count -gt 0 ]]; then log "INFO" "Organized $file_count ROM(s) for region: $region" fi } # Function to organize ROMs by kind within a specific folder # This is used for recursive kind organization organize_kind_in_location() { local inFolder=$1 local kind=$2 local context="${3:-root}" # For logging # Define kind directory within this folder local kindDir="${inFolder}/By Kind/${kind}" local file_count=0 # Find ROMs in THIS folder only (maxdepth 1) that match the kind pattern find "$inFolder" -maxdepth 1 -type f -name "*[\[(,]$kind[\]),]*" ! -name "*.m3u" -print0 | while IFS= read -r -d '' file; do # Create kind directory only when first file is found if [[ ! -d "$kindDir" ]]; then create_directory "$kindDir" log "INFO" "Created kind directory: $kind in $context" fi move_with_playlist "$file" "$kindDir" ((file_count++)) done # Only log if files were found if [[ $file_count -gt 0 ]]; then log "INFO" "Organized $file_count '$kind' ROM(s) in $context" fi } # Function to organize all kinds within a specific folder (recursively) organize_kinds_in_folder() { local target_folder=$1 local context="${2:-root}" # For logging: "root", "region:USA", "language:En" log "DEBUG" "Organizing kinds in $context folder" for kind in "${!GLOBAL_KINDS[@]}"; do # Check if this kind should be kept in place (not organized) if [[ -n "$KEEP_IN_ROOT_KINDS" && ",${KEEP_IN_ROOT_KINDS}," == *",${kind},"* ]]; then log "DEBUG" "Skipping '$kind' organization in $context (kept in place)" continue fi # NOT kept - organize this kind into subfolder organize_kind_in_location "$target_folder" "$kind" "$context" done } # Function to organize ROMs by kind (deprecated - use organize_kinds_in_folder) organize_kind() { local inFolder=$1 local kind=$2 log "INFO" "Organizing ROMs by kind: $kind" # Define kind directory (created on-demand) local kindDir="${inFolder}/By Kind/${kind}" local file_count=0 # Move ROMs matching the kind pattern find "$inFolder" -type f -name "*[\[(,]$kind[\]),]*" ! -name "*.m3u" -print0 | while IFS= read -r -d '' file; do # Create kind directory only when first file is found if [[ ! -d "$kindDir" ]]; then create_directory "$kindDir" log "INFO" "Created kind directory: $kind" fi move_with_playlist "$file" "$kindDir" ((file_count++)) done # Only log if files were found if [[ $file_count -gt 0 ]]; then log "INFO" "Organized $file_count ROM(s) for kind: $kind" fi } ################################################################################ # Language symlink organization functions ################################################################################ # Function to detect languages in a ROM filename detect_rom_languages() { local filename="$1" local -a languages_found=() # Check each language code in the filename for lang_code in "${LANGUAGE_ARRAY[@]}"; do # Match language codes in parentheses: (En) or (En,Fr) etc. if [[ "$filename" =~ [\(,]${lang_code}[,\)] ]]; then languages_found+=("$lang_code") fi done # Return array as space-separated string echo "${languages_found[@]}" } # Function to detect region from ROM filename detect_rom_region_from_file() { local filename="$1" local region="" # Check each region in REGION_ARRAY for check_region in "${REGION_ARRAY[@]}"; do if [[ "$filename" =~ \(${check_region}\) ]]; then region="$check_region" break fi done echo "$region" } # Function to create language symlinks for all ROMs organize_languages_by_symlinks() { local inFolder="$1" log "INFO" "Creating language symlink folders..." # Track which language folders we've created declare -A created_lang_folders local total_symlinks=0 # Find ALL ROM files recursively while IFS= read -r -d '' rom_file; do local filename filename=$(basename "$rom_file") # Detect region of this ROM local rom_region rom_region=$(detect_rom_region_from_file "$filename") # Check if this region should be excluded from language symlinks if [[ -n "$LANGUAGE_EXCLUDE_REGIONS" && -n "$rom_region" ]]; then if [[ ",${LANGUAGE_EXCLUDE_REGIONS}," == *",${rom_region},"* ]]; then log "DEBUG" "Skipping language symlinks for $filename (region $rom_region excluded)" continue fi fi # Detect languages in this ROM local languages languages=$(detect_rom_languages "$filename") if [[ -z "$languages" ]]; then continue # No languages detected fi # Create symlink for each language for lang_code in $languages; do # Get full language name local lang_name="${LANGUAGE_NAMES[$lang_code]}" if [[ -z "$lang_name" ]]; then log "WARN" "No language name mapping for code: $lang_code" lang_name="$lang_code" # Fallback to code fi # Create language folder if needed local lang_folder="${inFolder}/By Language/${lang_name}" if [[ ! -d "$lang_folder" ]]; then if [[ "$DRY_RUN" != "true" ]]; then create_directory "$lang_folder" fi log "INFO" "Created language folder: $lang_name" created_lang_folders["$lang_name"]=1 fi # Create symlink local symlink_path="${lang_folder}/${filename}" # Calculate relative path from symlink to original file local relative_path relative_path=$(realpath --relative-to="$lang_folder" "$rom_file" 2>/dev/null || echo "$rom_file") if [[ "$DRY_RUN" == "true" ]]; then log "DEBUG" "Would create symlink: $symlink_path -> $relative_path" else if [[ ! -e "$symlink_path" ]]; then ln -s "$relative_path" "$symlink_path" 2>/dev/null || { log "WARN" "Failed to create symlink: $symlink_path" continue } log "DEBUG" "Created symlink: ${lang_name}/${filename}" ((total_symlinks++)) fi fi done done < <(find "$inFolder" -type f \( -iname "*.nes" -o -iname "*.sfc" -o -iname "*.smc" -o -iname "*.md" -o -iname "*.zip" -o -iname "*.7z" \) ! -path "*/By Language/*" -print0) if [[ ${#created_lang_folders[@]} -gt 0 ]]; then log "INFO" "Created ${#created_lang_folders[@]} language folder(s) with $total_symlinks symlink(s)" else log "INFO" "No language folders created (no matching ROMs found)" fi } # Function to organize ROMs based on KEEP_IN_ROOT_* environment variables organize_roms() { local inFolder=$1 log "INFO" "Starting ROM organization in: $inFolder" log "INFO" "==========================================" # Validate KEEP_IN_ROOT settings validate_keep_in_root_settings || return 1 # Log configuration if [[ -v KEEP_IN_ROOT_REGIONS ]]; then log "INFO" "Region organization enabled (keep in root: ${KEEP_IN_ROOT_REGIONS:-none})" else log "INFO" "Region organization disabled (KEEP_IN_ROOT_REGIONS not set)" fi if [[ -v KEEP_IN_ROOT_KINDS ]]; then log "INFO" "Kind organization enabled (keep in place: ${KEEP_IN_ROOT_KINDS:-none})" else log "INFO" "Kind organization disabled (KEEP_IN_ROOT_KINDS not set)" fi if [[ "$ORGANIZE_LANGUAGES_BY_SYMLINK" == "true" ]]; then log "INFO" "Language symlink organization enabled (exclude regions: ${LANGUAGE_EXCLUDE_REGIONS:-none})" else log "INFO" "Language symlink organization disabled" fi log "INFO" "==========================================" # Phase 1: Region organization if [[ -v KEEP_IN_ROOT_REGIONS ]]; then log "INFO" "Phase 1: Processing regions" # Get region array (support both naming conventions) local -a regions if declare -p regionArray >/dev/null 2>&1; then regions=("${regionArray[@]}") else regions=("${REGION_ARRAY[@]}") fi for region in "${regions[@]}"; do # Check if this region should be kept in root if [[ -n "$KEEP_IN_ROOT_REGIONS" && ",${KEEP_IN_ROOT_REGIONS}," == *",${region},"* ]]; then log "DEBUG" "Keeping '$region' in root (not organizing)" continue fi # Not kept - organize it organize_region "$inFolder" "$region" done fi # Phase 2: Recursive kind organization if [[ -v KEEP_IN_ROOT_KINDS ]]; then log "INFO" "Phase 2: Processing kinds recursively" # Organize kinds in root folder organize_kinds_in_folder "$inFolder" "root" # Organize kinds in each region folder if [[ -d "$inFolder/By Region" ]]; then for region_dir in "$inFolder/By Region"/*; do if [[ -d "$region_dir" ]]; then local region_name=$(basename "$region_dir") organize_kinds_in_folder "$region_dir" "region:$region_name" fi done fi fi # Phase 3: Language symlink organization if [[ "$ORGANIZE_LANGUAGES_BY_SYMLINK" == "true" ]]; then log "INFO" "Phase 3: Creating language symlinks" organize_languages_by_symlinks "$inFolder" fi log "INFO" "==========================================" log "INFO" "ROM organization completed successfully" } # Main script execution main() { local inFolder="" # Parse options while [[ "$#" -gt 0 ]]; do case $1 in --dry-run ) DRY_RUN=true; log "DEBUG" "DRY_RUN set to true" ;; -h | --help ) display_usage ;; * ) inFolder=$1 ;; esac shift done # Export DRY_RUN for use in utils.sh functions export DRY_RUN # Check if inFolder was provided if [[ -z "$inFolder" ]]; then log "ERROR" "No directory specified" display_usage exit 1 fi # Display dry-run notice if [[ "$DRY_RUN" == "true" ]]; then log "INFO" "==========================================" log "INFO" "DRY-RUN MODE: No files will be modified" log "INFO" "==========================================" fi # Validate input folder validate_directory "$inFolder" # Organize ROMs (behavior controlled by KEEP_IN_ROOT_* environment variables) organize_roms "$inFolder" # Display completion message if [[ "$DRY_RUN" == "true" ]]; then log "INFO" "==========================================" log "INFO" "DRY-RUN COMPLETE: Preview finished" log "INFO" "Re-run without --dry-run to apply changes" log "INFO" "==========================================" fi } # Run the main function only if script is executed directly (not sourced) if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main "$@" fi