#!/bin/bash ################################################################################ # Library: utils.sh # Description: A shared library of utility functions for ROM management scripts. # Includes functions for directory management, file operations, # parameter validation, and more. # # Usage: Source this library in your script: # source "$(dirname "$(realpath "$0")")/utils.sh" # # Dependencies: # - logger.sh for consistent and color-coded logging. # - config.sh for configuration variables. ################################################################################ # Load logger and config from the core directory # These should already be loaded by the calling script, but just in case if [ -z "$LOGGER_LOADED" ]; then source "$(dirname "$(realpath "$0")")/logger.sh" fi if [ -z "$CONFIG_LOADED" ]; then source "$(dirname "$(realpath "$0")")/config.sh" fi # Function to URL encode a string urlencode() { local string="$1" local encoded encoded=$(curl -s -o /dev/null -w '%{url_effective}' --get --data-urlencode "$string" "") echo "${encoded##/?}" } # Function to URL decode a string urldecode() { local string="$1" printf '%b\n' "${string//%/\\x}" } # Function to validate if a path is within $EMUBASEDIR validate_path_within_emubasedir() { local path=$1 local emubasedir_resolved=$(realpath "$EMUBASEDIR" 2>&1) log "DEBUG" "Resolved EMUBASEDIR: $emubasedir_resolved" if [ $? -ne 0 ]; then log "ERROR" "Failed to resolve EMUBASEDIR: $emubasedir_resolved" return 1 fi # Manually resolve the path components local resolved_path="$path" while [ ! -d "$resolved_path" ]; do resolved_path=$(dirname "$resolved_path") done resolved_path=$(realpath "$resolved_path")/$(basename "$path") log "DEBUG" "Resolved path: $resolved_path" if [[ "$resolved_path" != "$emubasedir_resolved"* ]]; then log "ERROR" "Path is outside of EMUBASEDIR: $resolved_path" return 1 fi log "DEBUG" "Path is within EMUBASEDIR: $resolved_path" return 0 } # Function to validate if a directory exists validate_directory() { local path=$1 validate_path_within_emubasedir "$path" if [ ! -d "$path" ]; then log "ERROR" "Directory does not exist: $path" exit 1 fi } # Function to create a directory if it doesn't exist create_directory() { local path=$1 validate_path_within_emubasedir "$path" if [ ! -d "$path" ]; then log "DEBUG" "Creating directory: $path" mkdir -p "$path" || { log "ERROR" "Failed to create directory: $path"; exit 1; } fi } # Function to clean a directory (delete all files) clean_directory() { local path=$1 validate_path_within_emubasedir "$path" log "DEBUG" "Cleaning directory: $path" rm -rf "$path"/* || { log "ERROR" "Failed to clean directory: $path"; exit 1; } } # Function to copy files from source to destination copy_files() { local src=$1 local dest=$2 # Validate paths validate_path_within_emubasedir "$src" validate_path_within_emubasedir "$dest" # Check if dry-run mode is enabled if [[ "${DRY_RUN:-false}" == "true" ]]; then local file_count=$(find "$src" -mindepth 1 -maxdepth 1 | wc -l) log "INFO" "[DRY-RUN] Would copy $file_count files from $src to $dest" if [ "$DELETE" = true ]; then log "INFO" "[DRY-RUN] Would clean destination directory first (DELETE flag set)" fi log "INFO" "[DRY-RUN] Would create destination directory: $dest" return 0 fi # Create the destination directory log "DEBUG" "Creating destination directory: $dest" mkdir -p "$dest" || { log "ERROR" "Failed to create directory: $dest"; exit 1; } # If DELETE flag is set, clean the destination directory first if [ "$DELETE" = true ]; then log "DEBUG" "DELETE flag is set - cleaning destination directory" find "$dest" -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null || true fi # Load progress library if available if [[ -f "${SCRIPT_DIR:-$(dirname "${BASH_SOURCE[0]}")}/progress.sh" ]]; then source "${SCRIPT_DIR:-$(dirname "${BASH_SOURCE[0]}")}/progress.sh" 2>/dev/null || true fi # Count total files for progress tracking local total_files=$(find "$src" -mindepth 1 -maxdepth 1 | wc -l) local current_file=0 # Start progress tracking if available if command -v progress_batch_start >/dev/null 2>&1; then progress_batch_start "Copy" "$total_files" else echo "Starting Copy ($total_files items)" fi # Copy files from source to destination log "DEBUG" "Copying files from $src to $dest" local current_file=0 while IFS= read -r -d '' file; do current_file=$((current_file + 1)) # Update progress if available if command -v progress_batch_update >/dev/null 2>&1; then local filename=$(basename "$file") progress_batch_update "$filename" "processing" fi log "DEBUG" "Copying file: $file" if cp -r "$file" "$dest/" 2>/dev/null; then if command -v progress_batch_update >/dev/null 2>&1; then local filename=$(basename "$file") progress_batch_update "$filename" "success" fi else log "ERROR" "Failed to copy file: $file" if command -v progress_batch_update >/dev/null 2>&1; then local filename=$(basename "$file") progress_batch_update "$filename" "failed" fi fi done < <(find "$src" -mindepth 1 -maxdepth 1 -print0) # Finish progress tracking if command -v progress_batch_finish >/dev/null 2>&1; then progress_batch_finish "completed" fi log "INFO" "Files copied successfully from $src to $dest" } # Function to delete files matching a pattern in a directory delete_files() { local path=$1 local pattern=$2 validate_path_within_emubasedir "$path" # Check if dry-run mode is enabled if [[ "${DRY_RUN:-false}" == "true" ]]; then local file_count=$(find "$path" -type f -name "$pattern" | wc -l) log "INFO" "[DRY-RUN] Would delete $file_count files matching '$pattern' in $path" return 0 fi log "DEBUG" "Deleting files matching $pattern in $path" find "$path" -type f -name "$pattern" -print0 | xargs -0 rm -f || { log "ERROR" "Failed to delete files in $path"; exit 1; } } # Function to move files from source to destination move_files() { local src=$1 local dest=$2 validate_path_within_emubasedir "$src" validate_path_within_emubasedir "$dest" log "DEBUG" "Moving files from $src to $dest" mkdir -p "$dest" || { log "ERROR" "Failed to create directory: $dest"; exit 1; } #find "$src" -mindepth 1 -maxdepth 1 -print0 | xargs -0 -I {} mv "{}" "$dest/" || { log "ERROR" "Failed to move files from $src to $dest"; exit 1; } find "$src" -mindepth 0 -maxdepth 0 -print0 | xargs -0 -I {} mv "{}" "$dest/" || { log "ERROR" "Failed to move files from $src to $dest"; exit 1; } } # Move a ROM file and, if present, its associated multi-disc .m3u playlist. # Logic: derive a base name by stripping the first encountered disc marker pattern # (Disc|Disk|CD|Part|Episode|Vol) and anything following, then look # for a .m3u with that base in the same directory. If found and not already in # destination, move it ahead of moving the disc (so subsequent discs won't race). move_with_playlist() { local src_file=$1 local dest_dir=$2 if [ ! -f "$src_file" ]; then log "WARN" "move_with_playlist: source is not a file: $src_file" return 0 fi local dir base fname playlist_base playlist_file dir=$(dirname "$src_file") fname=$(basename "$src_file") # Ignore if this is already a playlist if [[ $fname == *.m3u ]]; then move_files "$src_file" "$dest_dir" return 0 fi base="${fname%.*}" # Extract portion before disc marker playlist_base=$(echo "$base" | sed -E 's/ \((Disc|Disk|CD|Part|Episode|Vol) ?[0-9IVX0]+\).*//I') # Reconstruct expected playlist filename playlist_file="${dir}/${playlist_base}.m3u" if [ -f "$playlist_file" ]; then # If destination already has playlist, skip moving it again if [ ! -f "$dest_dir/$(basename "$playlist_file")" ]; then log "DEBUG" "Moving associated playlist $(basename "$playlist_file") with $fname" move_files "$playlist_file" "$dest_dir" fi fi move_files "$src_file" "$dest_dir" } # Function to validate required parameters validate_parameters() { local params=("$@") for param in "${params[@]}"; do if [ -z "$param" ]; then log "ERROR" "Missing required parameter: $param" return 1 fi done return 0 } # Function to display a summary of the script's execution display_summary() { local success_count=$1 local failure_count=$2 local failed_files=("${@:3}") log "INFO" "Summary:" log "INFO" " Successfully processed files: $success_count" log "INFO" " Failed files: $failure_count" if [ "$failure_count" -gt 0 ]; then log "INFO" "Files that failed:" for file in "${failed_files[@]}"; do log "INFO" " $file" done fi } # Function to run a script with arguments run_script() { local script_path=$1 shift local args=("$@") log "DEBUG" "Running script: $script_path with args: ${args[@]}" "$script_path" "${args[@]}" } # Function to prompt the user in interactive mode prompt_user() { local step=$1 local description=$2 shift 2 local command="$@" if [ "$INTERACTIVE" = true ]; then log "INFO" "$step - $description" read -p "Press [Enter] to continue, [S] to skip..." choice if [ "$choice" = "S" ] || [ "$choice" = "s" ]; then log "INFO" "Skipping $step" return fi else log "INFO" "$step - $description" fi log "DEBUG" "Executing command: $command" eval "$command" || { log "ERROR" "Failed to execute command: $command"; exit 1; } }