#! /bin/bash

storiesfolder=${1%/}
chaptersfolder=${2%/}

# Walk through book folders in stories
for bookfolder in $storiesfolder/book*; do
    if [ -d $bookfolder ]; then
        bookname=$(basename $bookfolder)
        if [ ! -d $chaptersfolder/$bookname ]; then
            mkdir $chaptersfolder/$bookname
        fi
        for storypath in $bookfolder/*.html; do
            # \I+\.\d+
            storyname=$(basename "${storypath}")
            if [ ! -f "${chaptersfolder}/${bookname}/${storyname}" ]; then
                echo "Making chapter for ${storyname}"
                if [ -f "${chaptersfolder}/${bookname}/template.html" ]; then
                    echo "With template ${chaptersfolder}/${bookname}/template.html"
                    cp "${chaptersfolder}/${bookname}/template.html" "${chaptersfolder}/${bookname}/${storyname}"
                else
                    echo "With template ${chaptersfolder}/template.html"
                    cp "${chaptersfolder}/template.html" "${chaptersfolder}/${bookname}/${storyname}"
                fi

                escapedpath=$(sed "s|/|\\\/|g" <<< "${storypath}")
                head=$(sed -r "s/^(\I+\.[0-9]+(\.[0-9])*).*$/\1/g" <<< "${storyname}")
                head=$(sed "s/\./\-/g" <<< "${head}")
                sed -i "s/__story_path__/\/${escapedpath}/g" "${chaptersfolder}/${bookname}/${storyname}"
                sed -i "s/<body>/<body id=\"${head}\">/g" "${chaptersfolder}/${bookname}/${storyname}"
            fi
        done
    fi
done
