#!/bin/bash
# Print mediawiki code chapter headings and timecodes from audiobook file
# Usage: mw_get_audiobook_chapters.sh [file] ([int offset])
# Input: arg1: path to audiobook
# Example: mw_get_audiobook_chapters.sh input.m4b
# Version: 0.1.0


fin="$1";
n=0
while read -r line; do
    if [[ $((n % 2)) -eq 0 ]]; then
        chap="$(sed -e 's/^0*//' <<< "$line")"; # remove leading zero
        printf "====%s====\n" "$chap"; # output wikicode header
    elif [[ $((n % 2)) -eq 1 ]]; then
        printf "%s\n\n" "$line"; # output timecode
    fi;
    #declare -p n line; # debug
    ((n++));
done < <(ffprobe -i "$fin" -print_format json -show_chapters -sexagesimal | \
             jq \
                 -r '.chapters[] | (.tags.title) + "\n" + (.start_time | gsub("\\.\\d+$"; "") )'
        );
