#!/usr/bin/env sh
#
# ffmpeg-genchapters - generate chapters meta data from directory of audio files
#
# Usage:
#
#     ffmpeg-genchapters /some/path/to/dir mp3
#     ffmpeg-genchapters /other/path/to/dir m4a
#
# Flag | Description
# ---- | -----------
# -h   | Show this screen.
# -x   | Enable xtrace debug logging.

# shellcheck disable=SC2250

while getopts ':hx' opt; do
  # shellcheck disable=SC2249
  case "${opt}" in
    h)
      awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
      exit 0
      ;;
    x)
      set -x
      ;;
    ?)
      printf "%s: Unrecognized option: '-%c'\n" "${0##*/}" "${OPTARG}" >&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

tgtdir="${1:?'Target directory required.'}"
tgtext="${2:?'Input files extension required.'}"

tgtfiles="${tgtdir}_files.txt"
tgtlist="${tgtdir}__list.txt"
tgtmeta="${tgtdir}__meta.txt"

if [ ! -e "${tgtfiles}" ]; then
  lr -t 'name ~~~ "*.'"$tgtext"'"' -on > "${tgtfiles}" "${tgtdir}"
else
  printf 'Reusing existing: %s\n' "${tgtfiles}" 1>&2
fi

if [ -e "${tgtlist}" ] || [ -e "${tgtmeta}" ]; then
  printf 'Files already exist:\n%s\n%s\n' "${tgtlist}" "${tgtmeta}" 1>&2
  exit 1
fi

printf ';FFMETADATA
title=%s
artist=Foobar
genre=Audiobook
;TIMEBASE is in seconds
' "${tgtdir}" >"${tgtmeta}"

start_time='0.000000'

lr -U - <"${tgtfiles}" | while read -r file; do
  title="${file#"$tgtdir"/}"
  title="${title%."$tgtext"}"

  duration="$(ffprobe -v 0 -show_entries format=duration -of compact=print_section=0:nokey=1 "${file}")"
  end_time="$(printf '%s + %s\n' "${start_time}" "${duration}" | bc)"

  printf '[CHAPTER]
TIMEBASE=1/1
START=%s
END=%s
title=%s
' "${start_time}" "${end_time}" "${title}" >>"${tgtmeta}"

  start_time="$(printf '%s + %s\n' "${start_time}" "${duration}" | bc)"
done

lr -U -Qf 'file %p\n' - <"${tgtfiles}" >"${tgtlist}"

printf 'Inspect the generated files, edit as needed, then pass to ffmpeg-m4b:
%s
%s
' "${tgtlist}" "${tgtmeta}" 1>&2
