#!/bin/bash
if [ ! -f "$1" ]; then
    echo "File $1 not found!"
    echo "Usage: make_latex.sh <markdown-file>"
    exit
fi 

NEWNAME=modified.md

echo "Preparing working dir..."
rm -rf workdir
mkdir workdir
cp "$1" "workdir/$NEWNAME"
cd workdir

echo "Generating modified Markdown file..."

#prefix every \ with a \
sed -i -e 's/\\\\ *$/\\\\\\\\/g' "$NEWNAME"

bat "$NEWNAME"

# prefix every individual _ with an \
sed -i -e 's/_([^_])/\\_\1/g' "$NEWNAME"

bat "$NEWNAME"

# remove tags section at the front
sed -i -e 's/tags:.*//g' "$NEWNAME"
sed -i -e 's/---$//g' "$NEWNAME"

#remove markdown links
sed -i -e 's/\[.*\](.*)//g' "$NEWNAME"

# remove code block lang declaration
sed -i -e 's/```.*/```/g' "$NEWNAME"

bat "$NEWNAME"

# add newlines around code block declaration
sed -i -e 's/``` *$/\n```\n/g' "$NEWNAME"

bat "$NEWNAME"

# replace special HTML tags
sed -i -e 's/<div id="page-break-after"\/>/\\pagebreak/g' "$NEWNAME"
sed -i -e 's/<br>/\\newline/g' "$NEWNAME"

# remove html tags
sed -i -e 's/<[a-zA-Z ]*>\(.*\)<\/[a-zA-Z =]*>/\1/g' "$NEWNAME"
sed -i -e 's/<.*\/>//g' "$NEWNAME"
sed -i -e 's/<.*>//g' "$NEWNAME"

# replace arrows
sed -i -e 's/->/$\\rightarrow$/g' "$NEWNAME"
sed -i -e 's/<-/$\\leftarrow$/g' "$NEWNAME"
sed -i -e 's/=>/$\\Rightarrow$/g' "$NEWNAME"
sed -i -e 's/<=/$\\Leftarrow$/g' "$NEWNAME"

bat "$NEWNAME"

echo "Generating LaTeX file..."
echo "\documentclass[a4paper, 11pt]{article}

\usepackage[hybrid]{markdown}

\begin{document}
\markdownInput{$NEWNAME}
\end{document}" > file.tex

echo "Installing packages..."
tlmgr install markdown

echo "Building PDF..."
pdflatex -synctex=1 -interaction=nonstopmode --shell-escape file.tex

cp *.pdf ..

echo "Done."