#! /bin/bash
sourcefolder=${1%/}
putfolder=${2%/}

if [ ! -d $putfolder ]; then
    echo "Making putfolder"
    mkdir "${putfolder}"
fi

for book in $sourcefolder/book*; do
    echo "Reading ${book}"
    bookfolder=$putfolder/$(basename "${book}")
    
    if [ ! -d $bookfolder ]; then
        mkdir "${bookfolder}"
    fi
    
    for mdfile in $book/*.md; do
        htmlfile=$(basename -s .md "${mdfile}")

        if [ ! -f "${bookfolder}/${htmlfile}.html" ]; then
            # Convert to HTML through pandoc. Store as temporary file
            pandoc "${mdfile}" -r markdown -t html -s -o "${bookfolder}/${htmlfile}.tmp.html"
            # Grab only the content within the body tags
            cat "${bookfolder}/${htmlfile}.tmp.html" | awk '/<body>/,/<\/body>/' | sed 's/<body>//' | sed 's/<\/body>//' > "${bookfolder}/${htmlfile}.html"
            # Remove the tmp-files
            rm -f "${bookfolder}/${htmlfile}.tmp.html"
            echo "${mdfile} > ${bookfolder}/${htmlfile}.html"
        else
            echo "${bookfolder}/${htmlfile}.html already exists"
        fi
    done;
done;

echo "Applying extra line breaks"