#! /bin/bash

chapterfolder=${1%/}
srcjs=$2

echo ";(function(undefined) {" > "${srcjs}"
echo "    'use strict';" >> "${srcjs}"
echo "    var src = {" >> "${srcjs}"


for bookfolder in $chapterfolder/book*; do
    if [ -d $bookfolder ]; then
        for htmlfile in $bookfolder/*.html; do
            filepath=$(sed "s/^..\//\//g" <<< "${htmlfile}")
            filename=$(basename -s .html "${htmlfile}")
            splitname=$(sed "s/-/ /g" <<< "${filename}")
            name=$(sed -e "s/\([a-z]\)\([0-9]\)/\1 \2/gi" <<< "${splitname}")
            if [ "${name}" != "template" ]; then
              echo "${name}: ${filepath} "
              echo "        \"${name}\": \"${filepath}\","  >> "${srcjs}"
            fi
        done;
    fi
done;

echo "    }" >> "${srcjs}"
echo "    var docs = new HTML2print.Docs;" >> "${srcjs}"
echo "    docs.initialize(src);" >> "${srcjs}"
echo "})();" >> "${srcjs}"

echo "Written to ${srcjs}"
