MD_FILE="$1"

BASE_DIR="$(pwd)"
PDF_FILE="${BASE_DIR}/pdf/$(basename "$MD_FILE" | sed -e 's/\.md$/.pdf/')"
BUILD_DIR="${BASE_DIR}/build/$(basename "$MD_FILE" | sed -e 's/\.md$//')"
TEMP_MD_FILE="$BUILD_DIR/$(basename "$MD_FILE")"

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 "download remote image: $src"

        mkdir -p "${BASE_DIR}/pdf/images"
        name=$(echo "$src" | sed -e 's|^.*/\([^/]*\)$|\1|')
        if [[ ! -f "${BASE_DIR}/pdf/images/$name" ]]
        then
            curl "$src" >"${BASE_DIR}/pdf/images/$name"
        else
            echo "  image already exists"
        fi
        sed -i "$1" -e "s|$src|${BASE_DIR}/pdf/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"

    cp "$(pwd)$md_src" "$BUILD_DIR/$(basename "$md_src")"

    download_images "$BUILD_DIR/$(basename "$md_src")"

    sed -i "$BUILD_DIR/$(basename "$md_src")" \
        -e 's|\[toc\]||' \
        -e 's|^\[parent\].*$||' \
        -e "s|\`\`\`mermaid|\`\`\`{.mermaid loc=${BASE_DIR}/pdf/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|\`\`\`mermaid|\`\`\`{.mermaid loc=${BASE_DIR}/pdf/images/$(basename "$MD_FILE")}|"

mkdir -p ${BASE_DIR}/pdf/images/$(basename "$MD_FILE")
cd "$BUILD_DIR"
pandoc --standalone \
    --lua-filter=../../converters/include-files.lua \
    --lua-filter=../../converters/headers.lua \
    -t latex --pdf-engine=xelatex \
    --from=markdown+abbreviations \
    --template "${BASE_DIR}/converters/template.latex" \
    -o "$PDF_FILE" \
    "$(basename "$TEMP_MD_FILE")"
cd "$BASE_DIR"
