#!/bin/bash
#
# du_sh_and_count - do both 'du -sh' and file count, with compact output and timing
#
# See the HELP_SCREEN variable in the source code for details.

# Load JXL. See "Loading JXL" in dots/README.md.
source "$(cd "$(dirname "$0")" && pwd -P)/../dots/all-os/flat/dotlib/jxl-lib.sh" \
    || { echo >&2 "ERROR: failed to load jxl-lib.sh"; exit 1; }

jxl::init_script
jxl::use_short_names
_JXL_EMIT_TIMESTAMP=1
_JXL_EMIT_PROGNAME=1

FILES=()

function parse_cmdline() {
  local arg

  while [[ $# -ge 1 ]]; do
    arg="$1"; shift
    case "$arg" in
      -*)
        jxl::std_opt "$arg" || die "Unexpected option: ${arg}"
        if [[ $_JXL_WANT_HELP == 1 ]]; then echo "$HELP_SCREEN"; exit 0; fi
        ;;
      *)
        FILES+=("$arg")
        ;;
    esac
  done
}

# `readonly` goes after the read, not on the declaration: `read` can't write to a variable
# that is already readonly, and the `|| true` would swallow the resulting error, leaving
# the help screen silently empty.
HELP_SCREEN=''
IFS= read -r -d '' HELP_SCREEN <<EOHELP || true

${PROGRAM_NAME} - do both 'du -sh' and file count, with compact output and timing

Usage:
  ${PROGRAM_NAME} <dir> [<dir> ...]

Options:
$(jxl::std_options_help)
EOHELP
readonly HELP_SCREEN

function main() {
  parse_cmdline "$@"
  if [[ ${#FILES[@]} -eq 0 ]]; then
    die "No directories given. See '$PROGRAM_NAME --help' for usage"
  fi
  du_sh_and_count_files "${FILES[@]}"
}

# du_sh_and_count_files - do both 'du -sh' and file count, with compact output
function du_sh_and_count_files() {
  local -a dirs
  local dir size n_files width t0 te
  forbid_dry_run
  dirs=("$@")
  width=$(max_strlen "${dirs[@]}" '        ')
  width=$(( width + 1 ))
  for dir in "${dirs[@]}"; do
    dir="${dir%/}"
    t0=$(tick)
    printf '%-*s   ' $width "${dir}:"
    size=$(du -sh "$dir" | cut -f 1)
    printf '%6s ' "$size"
    n_files=$(find "$dir" | wc -l)
    te=$(tock "$t0")
    printf '%10s files + dirs   (%s)' "$(jxl::thous "$n_files")" "$(s2mmss "$te")"
    printf '\n'
  done
}


# ========== Main script ==========

main "$@"
exit $?
