#!/bin/sh
#
# dependencies: ffmpeg | mediainfo

if [ "$#" -eq 0 ]; then
  if command -v mediainfo >/dev/null 2>&1; then
    find "${@:-.}" \
      -type f \
      -exec mediainfo --Output='General;%Duration%\n' {} \; \
      | awk '{ x += $0 } END { printf "%0.2f hours\n", x / 1000 / 60 / 60 }'
    exit
  else
    printf '%s\n' "${0##*/} [video-file]" >&2
    exit 1
  fi
fi

if [ "$#" -gt 0 ]; then
  if [ -d "$1" ]; then
    if command -v mediainfo >/dev/null 2>&1; then
      for d in "$@"; do
        find "${d}" \
          -type f \
          -exec mediainfo --Output='General;%Duration%\n' {} \; \
          | awk '{ x += $0 } END { printf "%0.2f hours\n", x / 1000 / 60 / 60 }'
      done
    else
      printf '%s\n' "Usage: ${0##*/} video-file" >&2
      exit 1
    fi
  else

    fp="$1"
    out="$(ffprobe -loglevel error -show_format "${fp}")"

    # shellcheck disable=SC2181
    if [ "$?" != 0 ]; then
      echo "${out}" >&2
      exit 1
    fi

    python3 <<EOF
from __future__ import division, print_function
import re

m = re.search(r"duration=(\d+)", """${out}""")
seconds = int(m.group(1))

hours = seconds // 3600
seconds -= hours * 3600

minutes = seconds // 60
seconds -= minutes * 60

print("%dh%dm%ds" % (hours, minutes, seconds))
EOF
  fi
fi
