Music-DeDuper/cleaner.sh
2025-03-10 09:47:35 +01:00

81 lines
2.3 KiB
Bash
Executable File

#!/bin/bash
dry_run=true # Default to dry-run mode
if [[ "$1" == "--armed" ]]; then
dry_run=false
fi
declare -A folders
# Function to detect bit-depth and sample rate
detect_quality() {
if [[ "$1" =~ ([0-9]+)B-([0-9]+(\.[0-9]+)?)kHz ]]; then
bit_depth="${BASH_REMATCH[1]}"
sample_rate=$(echo "${BASH_REMATCH[2]}" | awk '{printf "%d", $1 * 10}') # Convert to integer
echo "$bit_depth $sample_rate"
else
echo ""
fi
}
# Function to compare quality (Higher value wins)
compare_quality() {
local quality1=($1)
local quality2=($2)
# Prioritize higher bit-depth (24-bit > 16-bit)
if [[ ${quality1[0]} -gt ${quality2[0]} ]]; then
echo 1
return
elif [[ ${quality1[0]} -lt ${quality2[0]} ]]; then
echo -1
return
fi
# If bit-depth is the same, prioritize higher sample rate
if [[ ${quality1[1]} -gt ${quality2[1]} ]]; then
echo 1
else
echo -1
fi
}
for dir in *; do
if [[ -d "$dir" ]]; then
# Normalize base name by removing bit-depth, sample rate, and extra spaces
base_name=$(echo "$dir" | sed -E 's/\s*\[FLAC\]\s*\[[0-9]+B-[0-9]+(\.[0-9]+)?kHz\]//')
# Extract quality information (bit-depth and sample rate)
quality=$(detect_quality "$dir")
# Skip if quality detection fails
if [[ -z "$quality" ]]; then
echo "Skipping (No quality detected): $dir"
continue
fi
if [[ -n "${folders[$base_name]}" ]]; then
existing_quality=${folders[$base_name]%::*}
existing_dir=${folders[$base_name]#*::}
comparison=$(compare_quality "$quality" "$existing_quality")
if [[ $comparison -eq 1 ]]; then
# New file is better -> Remove existing lower-quality version
echo "Removing lower-quality: $existing_dir"
[[ $dry_run == false ]] && rm -rf "$existing_dir"
folders[$base_name]="$quality::$dir"
else
# Keep existing better version -> Remove new lower-quality version
echo "Removing lower-quality: $dir"
[[ $dry_run == false ]] && rm -rf "$dir"
fi
else
folders[$base_name]="$quality::$dir"
fi
fi
done
echo "Dry-run mode: $dry_run. Use --armed to actually delete files."