MD_FILE="$1"

BASE_DIR="$(pwd)"
TEX_FILE="${BASE_DIR}/latex/$(basename "$MD_FILE" | sed -e 's/\.md$/.latex/')"
BUILD_DIR="${BASE_DIR}/build/$(basename "$MD_FILE" | sed -e 's/\.md$//')"
TEMP_MD_FILE="$BUILD_DIR/$(basename "$MD_FILE")"
TEMP_TEX_FILE="$BUILD_DIR/$(basename "$MD_FILE" | sed -e 's|md$|latex|')"
mkdir -p "$(dirname "$TEMP_MD_FILE")"

cp "$MD_FILE" "$TEMP_MD_FILE"

function download_images() {
    echo "download images for $1"
    for line in $(grep '!\[.*\](https://.*\.png)' "$1" | sed -e 's/ /%20;/g')
    do
        src=$(echo "$line" | sed -e 's/^.*(//' -e 's/).*$//' -e 's/%20;/ /g')
        echo "remote image found: $src"

        mkdir -p "${BASE_DIR}/latex/images"
        name=$(echo "$src" | sed -e 's|^.*/\([^/]*\)$|\1|')
        curl "$src" > "${BASE_DIR}/latex/images/$name"
    done
    echo "download done"
}

for line in $(grep '^!\[.*\](.*\.md)$' "$TEMP_MD_FILE" | sed -e 's/ /%20;/g')
do
    md_src=$(echo "$line" | sed -e 's/^.*(//' -e 's/).*$//' -e 's/%20;/ /g')
    echo "include found: $md_src"

    download_images "$(pwd)$md_src"

    cp "$(pwd)$md_src" "$BUILD_DIR/$(basename "$md_src")"
    sed -i "$BUILD_DIR/$(basename "$md_src")" \
        -e 's|\[toc\]||' \
        -e 's|^\[parent\].*$||' \
        -e 's|\[\([^]]*\)\](#\([^)]*\))|[\1](#\L\2)|' \
        -e "s|https://live.kladjes.nl/uploads|${BASE_DIR}/latex/images|" \
        -e "s|\`\`\`mermaid|\`\`\`{.mermaid loc=${BASE_DIR}/latex/images/$(basename "$md_src")}|"

    sed -i "$TEMP_MD_FILE" \
        -e "s|^\!\[.*\]($md_src)\$|\`\`\`\\{.include shift-heading-level-by=1\\}\n$(basename "$md_src")\n\`\`\`|"

done

download_images "$TEMP_MD_FILE"

sed -i "$TEMP_MD_FILE" \
    -e 's|\[toc\]|\\tableofcontents|' \
    -e 's|^\[parent\].*$||' \
    -e 's|\[\([^]]*\)\](#\([^)]*\))|[\1](#\L\2)|' \
    -e "s|https://live.kladjes.nl/uploads|${BASE_DIR}/latex/images|" \
    -e "s|\`\`\`mermaid|\`\`\`{.mermaid loc=${BASE_DIR}/latex/images/$(basename "$MD_FILE")}|"

    # -e 's|```\([^ \t]\)=|```\1 {linenumbers}|'

mkdir -p ${BASE_DIR}/latex/images/$(basename "$MD_FILE")
cd "$BUILD_DIR"
pandoc \
    --lua-filter=../../converters/include-files.lua \
    --lua-filter=../../converters/headers.lua \
    --to=latex \
    --from=markdown+abbreviations \
    --template "${BASE_DIR}/converters/template.latex" \
    -o "$TEX_FILE" \
    --dpi 300 \
    "$(basename "$TEMP_MD_FILE")"
cd "$BASE_DIR"
