#!/bin/bash
# This script is meant to find duplicate files in a directory, even though
# they may have different file names. If the script finds duplicates that
# have different file names, it will list the shorter file name as the
# duplicate.

# mapfile -t list <'/home/lucifer/beos_duplicates_final.txt'

# for (( i = 0; i < ${#list[@]}; i++ )); do
# f=${list[${i}]}
# echo "*** ${f}"
# read yesno
# if [[ $yesno == 'y' ]]; then
# rm "$f" || break
# fi
# done

declare -A md5s md5s_2

declare -a library

for arg in "$@"; do
	if [[ -d $arg ]]; then
		library+=( "$(readlink -f "$arg")" )
	fi
done

if [[ -z ${library[0]} ]]; then
	echo -e "Usage: $(basename "$0") [dirs...]\n"
	exit
fi

mapfile -t files < <(find "${library[@]}" -type f -iname "*")

for (( i = 0; i < ${#files[@]}; i++ )); do
	md5=$(md5sum -b "${files[${i}]}" | cut -d' ' -f1)

	if [[ -z ${md5s[${md5}]} ]]; then
		md5s[${md5}]="${files[${i}]}"
	else
		length_if=$(basename "${md5s[${md5}]}" | wc -m | tr -d '[:blank:]')
		length_of=$(basename "${files[${i}]}" | wc -m | tr -d '[:blank:]')

		if [[ $length_of -gt $length_if ]]; then
			md5s[${md5}]="${files[${i}]}"
		fi
	fi

	if [[ -z ${md5s_2[${md5}]} ]]; then
		md5s_2[${md5}]='1'
	else
		(( md5s_2[${md5}] = md5s_2[${md5}] + 1 ))
	fi
done

for (( i = 0; i < ${#files[@]}; i++ )); do
	md5=$(md5sum -b "${files[${i}]}" | cut -d' ' -f1)

	if [[ ${md5s[${md5}]} != ${files[${i}]} && ${md5s_2[${md5}]} -gt 1 ]]; then
		echo "${files[${i}]}"
	fi
done
