#!/bin/sh
#
# ssize - shows size statistics for subfolders
# max depth is equal to the first argument if it is a number or 1

# shellcheck disable=SC2249

export chars=$(($(tput cols) - 60))

case "$1" in
  +*)
    size=${1#+}G
    depth=2
    shift
    ;;
esac

case "$1" in
  [0-9])
    depth=$1
    shift
    ;;
esac

# du="du --max-depth '${depth:-1}' -xha"
case "$(uname)" in
  Darwin)
    ducmd() {
      coreutils du --dereference --dereference-args \
        --max-depth "${depth:-1}" --one-file-system -ha
    }
    (ducmd -t "${size:-50M}" "$@" | sort -h | grep -v "^0") \
      | while read -r line; do
        # shellcheck disable=SC2312
        echo "$(tput smso)${line}$(tput rmso)"
      done \
      ||
      #| column -t ||
      (ducmd "$@" | sort -h | tail)
    ;;
  *)
    ducmd() {
      command du --dereference --dereference-args \
        --max-depth "${depth:-1}" --one-file-system -ha
    }
    # pacman -q -Qo
    # show related package and the binary path for installed packages
    # query the database to know which package a file in the file system belongs to
    # shellcheck disable=SC2312
    (ducmd -t "${size:-50M}" "$@" | sort -h | grep -v "^0") \
      | while read -r line; do
        # shellcheck disable=SC2046
        files=$(readlink --canonicalize $(echo "${line}" | awk '{ print $2 }'))
        echo "$(tput smso)${line}$(tput rmso) \
          $(dpkg --search "${files}" 2>/dev/null | paste -s -d',' \
          | sed "s/\(.\{${chars}\}\).*/\1.../")"
      done \
      || (ducmd "$@" | sort -h | tail)
    ;;
esac
