#!/usr/bin/zsh
set -e

alias git="${GIT:-/usr/bin/git}"

setopt -o nullglob

source "$CASILEDIR/lib/functions.zsh"

: ${bookid:=$1}
test -n bookid

: ${format:=$2}
test -n format

: ${input:=$3}
test -f $input

pandoc_args=(
	--to=markdown-yaml_metadata_block-smart
)

function import_scrivener-mmd () {
	pandoc_args+=(
		--lua-filter="$CASILEDIR/pandoc-filters/mark-parts.lua"
		--lua-filter="$CASILEDIR/pandoc-filters/mark-epigraphs.lua"
	)
	alias pandoc="${PANDOC:-/usr/bin/pandoc}"
	: ${bookid:=$1}
	: ${input:=$2}
	cat $input |
		normalize_scrivener_mmd |
		pandoc ${pandoc_args[@]} |
		normalize_pandoc > $bookid.md
}

function import_docx () {
	pandoc_args+=(
		--from=docx-gfm_auto_identifiers-ascii_identifiers-empty_paragraphs
		--lua-filter="$CASILEDIR/pandoc-filters/guess-headings.lua"
		--lua-filter="$CASILEDIR/pandoc-filters/unitalicize-blockquotes.lua"
	)
	alias pandoc="${PANDOC:-/usr/bin/pandoc}"
	: ${bookid:=$1}
	: ${input:=$2}
	pandoc $input ${pandoc_args[@]} |
		normalize_pandoc > $bookid.md
}

remove_extant_bookid $bookid

# Restore meta-data just (maybe) nuked
git checkout HEAD^ -- $bookid.yml $bookid.lua
git commit --amend --no-edit

track "$input"
commit 'Track file submitted for import (temporarily)'

import_${format} $bookid $input
track $bookid.md

untrack $input
commit "Import $format source as $bookid"

"$CASILEDIR/scripts/split_chapters.zsh" 3 $bookid
