#!/usr/bin/zsh
set -e

src=$1
dir=$2

alias pandoc="${PANDOC:-/usr/bin/pandoc}"
alias perl="${PERL:-/usr/bin/perl}"

echo -e "# Summary\n\n"

i=0
of=00.md

function trunc() {
  : > $1
}

trunc $dir/$of

while read line; do
  unset title slug
  # Check for chapter header
  if [[ $line =~ "^##? " ]]; then
    pandoc --to=plain-smart <<< "$line" |
      read title
    if [[ $line =~ "^# " ]]; then
      [[ $line =~ "\.unnumbered\b" ]] || let i=$i+1
      unset j
    else
      : ${j:=0}
      [[ $line =~ "\.unnumbered\b" ]] || let j=$j+1
      echo -n "    "
    fi
    # https://github.com/jgm/pandoc/issues/8003
    pandoc -f markdown+ascii_identifiers -t markdown-auto_identifiers <<< "# ${title//ı/i}" |
      perl -pne 's/^.*{.*#([-\w]+).*}/\1/' |
      read slug
    test -n "$slug"
    of="$(printf %02d $i)${j:+$(printf .%03d $j)}-$slug.md"
    trunc $dir/$of
    [[ $line =~ "\.unnumbered\b" ]] || echo -n "- "
    echo "[$title](./$of)"
    # Strip attrs we *used* via commonmark_x for our own use from markup going to mdbook
    pandoc --to=commonmark-smart <<< "$line" |
      read line
  fi
  >> $dir/$of <<< $line
done < $src

# Some "books" have no chapters. If we didn't find any, at least list the blob
if [[ $of = "00.md" ]]; then
  echo "[](./$of)"
fi
