#!/usr/bin/zsh
set -e

source "$CASILEDIR/lib/functions.zsh"

alias pandoc="${PANDOC:=/usr/bin/pandoc}"
alias sed="${SED:=/usr/bin/sed}"
alias mkdir="${MKDIR_P:=/usr/bin/mkdir -p}"
alias parallel="${PARALLEL:=/usr/bin/parallel}"
alias zsh="${ZSH:=/usr/bin/zsh}"

splitlevels=$1
test -n $splitlevels

bookid=$2
test -n $bookid

# TODO: restore support for top level being chapters instead of parts
part_no=0
chapter_no=0
section_no=0
of=$bookid.md
files=()

mkdir $BUILDDIR
src=$(mktemp $BUILDDIR/splitXXXXXX.md)
trap 'rm -rf $src' EXIT SIGHUP SIGTERM

mv $bookid.md $src
truncate -s0 $bookid.md

pandoc $src --markdown-headings=atx --wrap=none --to=markdown --reference-location=document |
while read -r line; do
	# Stop processing if we've hit footnotes
	[[ $line =~ "^\[\^1\]: .*" ]] && break

	# Check for headers
	if [[ $line =~ "^#+ .*" ]] || [[ $line =~ '^\\part\{.*\}$' ]]; then
		if [[ $line =~ '^\\part\{.*\}$' ]] && [[ $splitlevels -ge 1 ]]; then
			chapter_no=0
			section_no=0
			let part_no=$part_no+1
			dir=${bookid}-parts
			mkdir $dir
			of=$dir/$(printf %03d $part_no).md
		elif [[ $line =~ "^# " ]] && [[ $splitlevels -ge 2 ]]; then
			section_no=0
			[[ $line =~ ".*unnumbered.*" ]] || let chapter_no=$chapter_no+1
			dir=${bookid}-parts/$(printf %03d $part_no)-chapters
			mkdir $dir
			of=$dir/$(printf %03d $chapter_no).md
		elif [[ $line =~ "^## " ]] && [[ $splitlevels -ge 3 ]]; then
			[[ $line =~ ".*unnumbered.*" ]] || let section_no=$section_no+1
			dir=${bookid}-parts/$(printf %03d $part_no)-chapters/$(printf %03d $chapter_no)-sections
			mkdir $dir
			of=$dir/$(printf %03d $section_no).md
		elif [[ $splitlevels -ge 3 ]] then
			flunk 'Unsupported 3 level split'
		fi
		files+=($of)
	fi

	>> $of <<< "$line"
done

# Truncate source to just footnotes
sed -i -n -e '/^\[\^1\]: /,$p' $src

# Put footnotes in all files, renumber, and generally cleanup
function cleanup_split () {
	alias sponge="${SPONGE:-/usr/bin/sponge}"
	normalize_pandoc < $1 < $src | sponge $1
}
F=$(functions cleanup_split normalize_pandoc)
parallel $ZSH -c "$F; src=$src; cleanup_split" ::: ${files[@]}

track $bookid.md ${files[@]}
commit "Split $bookid up into chapters and sections"

"$CASILEDIR/scripts/normalize_files.zsh" $bookid
