#!/bin/bash
# compare_size_sha.sh - Find and optionally delete duplicate files by SIZE + SHA256

DIR="${1:-.}"
TMPFILE=$(mktemp)

echo "Scanning directory: $DIR"
echo "Step 1: Grouping files by size..."

# List all files with sizes
find "$DIR" -type f -printf "%s %p\n" | sort -n > "$TMPFILE.size"

# Only keep sizes with more than 1 file
awk '{
    count[$1]++
    files[$1] = files[$1] ? files[$1] ORS $2 : $2
}
END {
    for (s in count) {
        if (count[s] > 1) {
            print files[s]
        }
    }
}' "$TMPFILE.size" > "$TMPFILE.candidates"

echo "Step 2: Calculating SHA256 for files with duplicate sizes..."
> "$TMPFILE"

while read -r FILE; do
    sha256sum "$FILE"
done < "$TMPFILE.candidates" >> "$TMPFILE"

sort "$TMPFILE" -o "$TMPFILE"

echo ""
echo "Duplicate files (same size + SHA256):"
echo "------------------------------------"

awk '
{
    count[$1]++
    files[$1] = files[$1] ? files[$1] ORS $2 : $2
}
END {
    for (h in count) {
        if (count[h] > 1) {
            print "Hash: " h
            print files[h]
            print "------------------------------------"
        }
    }
}' "$TMPFILE"

echo ""
read -p "Delete duplicates and keep only the first copy? (y/N): " CONFIRM

if [[ "$CONFIRM" =~ ^[Yy]$ ]]; then
    echo ""
    echo "Deleting duplicates..."
    echo "------------------------------------"
    awk '
    {
        if (!seen[$1]) {
            seen[$1] = $2
        } else {
            print $1 " " $2
        }
    }' "$TMPFILE" | while read -r HASH DUPFILE; do
        KEEPFILE=$(awk -v h="$HASH" '
            $1==h && !seen { seen=1; print $2 }
        ' "$TMPFILE")
        echo "Keeping:  $KEEPFILE"
        echo "Deleting: $DUPFILE"
        rm -f "$DUPFILE"
        echo "------------------------------------"
    done
    echo "Done."
else
    echo "No files were deleted."
fi

rm -f "$TMPFILE" "$TMPFILE.size" "$TMPFILE.candidates"
