#!/bin/sh

PRG="${0##*/}"

usage () { echo "Usage: $PRG [dir]" >&2 ; exit 1 ; }

case $# in
  1)
    dir="$1"
    case "$1" in
      -* ) [ -e "$dir" ] || usage ;;
    esac
    ;;
  0) dir='.' ;;
  *) usage ;;
esac

# Find mount point for $dir.
mnt="$( df --o=target -- "$dir" | sed 1d )" \
  || { printf "%s: error: unable to find mount point for '%s'.\n" "$PRG" "$dir" >&2 ; \
       exit 1 ; }

# Get device number of that mount point.
dev="$( stat -c '%d' -- "$mnt" )" \
  || { printf "%s: error: unable to find device number for mount point '%s'.\n" "$PRG" "$dir" >&2 ;
       exit 1 ; }
printf "Mount point: '%s', device number (decimal): %s\n" "$mnt" "$dev" >&2

# Process every directory on the same device as $dir.
find "$mnt" -xdev -type d -print0 | \
xargs -0 env DEV="$dev" sh -c '
  while [ $# -gt 0 ] ; do
    f="$1"
    shift 1
    # Verify that we are still on the same file system.
    fdev="$( stat -c "%d" -- "$f" )" \
      || continue
    [ "$fdev" = "$DEV" ] \
      || { printf "0 %s [mount]\n" "$f" ; continue ; }
    # Count the number of files below.
    num="$( find "$f" -xdev | wc -l )"
    printf "%d %s\n" "$num" "$f"
  done
' | \
sort -k1,1n
