#!/bin/sh
#
# ,human - convert bytes to human readable format
#
# ex:
#    6579057657 -> '6.1G'
#    562952382  -> '536.8M'
#
# ---
# source: https://github.com/mitchweaver/bin

if [ -z "$1" ]; then
  read -r inp
  set -- "${inp}"
fi

if [ "$1" -gt 1099511627776 ]; then
  res=$(($1 * 10 / 1099511627776))
  pow=T
elif [ "$1" -gt 1073741824 ]; then
  res=$(($1 * 10 / 1073741824))
  pow=G
elif [ "$1" -gt 1048576 ]; then
  res=$(($1 * 10 / 1048576))
  pow=M
elif [ "$1" -gt 1024 ]; then
  res=$(($1 * 10 / 1024))
  pow=K
else
  printf '%sB\n' "${1:-0}"
  exit
fi

# shellcheck disable=SC2295
printf "%s${pow}\n" "${res%?}.${res#${res%?}}"
