#!/bin/bash

# information function
function info {
  echo 'This commands shows current usage of disk space in directories.'
  echo
  echo 'dutop <directory> [-m SIZE] [-h] [-n] [-r]'
  echo '   -m   defines size of the smallest displayed file (default 100M)'
  echo '   -h   human readable sizes output'
  echo '   -n   sort list by file path and name instead of size'
  echo '   -r   reverse the list'
  echo
}

# set default parameters
HUMAN_READABLE=0
SORT_BY_NAME=0
MINIMUM_SIZE="100M"
REVERSED=0

# get destination directory
DIRECTORY="$1"
shift

# init options
DU_OPTS=()
SORT_OPTS=()

# if no directory provided
if [[ -z "${DIRECTORY}" ]] || [[ ! -d "${DIRECTORY}" ]]
then
  info
  echo 'Error: No valid directory was specified!'
  echo
  exit 1
fi

# read switches
while [[ $# -gt 0 ]]
do
  key="$1"
  case ${key} in
      -m|--minimum-size)
      MINIMUM_SIZE="$2"
      shift
      ;;
      -h|--human-readable)
      HUMAN_READABLE=1
      ;;
      -n|--sort-by-name)
      SORT_BY_NAME=1
      ;;
      -r|--reversed)
      REVERSED=1
      ;;
      *)
      info
      exit 1
      ;;
  esac
  shift
done

# create options
if [[ ${HUMAN_READABLE} == 1 ]]
then
  DU_OPTS+=('h')
fi

if [[ ${SORT_BY_NAME} == 1 ]]
then
  SORT_OPTS+=(-k2)
else
  SORT_OPTS+=(--human-numeric-sort)
fi

if [[ ${REVERSED} == 0 ]]
then
  SORT_OPTS+=(-r)
fi

find "${DIRECTORY}" -type f -size +"${MINIMUM_SIZE}" \
  -exec du -s"${DU_OPTS[@]}" {} \; | sort "${SORT_OPTS[@]}"
