#!/bin/sh
# Compiler script for groff
#
# TODO:
# Make groff auto-calculate image height (spacing below)
# based on given width and the image's aspect ratio
#
# [-k (preconv)] Convert encoding to something groff understands
# [-e (eqn)]     Format equations for troff or MathML
# [-t (tbl)]     Format tables for troff
# [-p (pic)]     Compile pictures for troff or TeX
# [-G (grap)]    Typesetting graphs, usually not installed by default and not available on termux repo
# [-j (chem)]    Chemical structure diagrams, messes with spacing, crashes when using text inside eqn

# Configuration
BIB="$HOME/Documents/bibliography" # Bibliography file
MAC="$HOME/.config/groff/"         # Macros dir
PRE="-ketpG"                       # Preprocessors

# Takes a line with .IMG command, converts given image
# to pdf format and inserts properly formatted .PDFPIC
auto_pdfpic() {
    LINE="$1"
    IMAGE="$(echo "$LINE" | cut -d '"' -f 2)"
    [ "$IMAGE" != "${IMAGE%%.*}.pdf" ] && ! [ -e "${IMAGE%%.*}.pdf" ] &&
        convert -quiet "$IMAGE" "${IMAGE%%.*}.pdf"
    echo "$LINE" | sed 's|^.IMG|.PDFPIC|' | sed "s|$IMAGE|${IMAGE%%.*}.pdf|"
}

# If there is any .IMG command, replace with
# auto_pdfpic output in a temp file.
FILE="$1"
if [ "$(grep '^.IMG\s' "$FILE")" ] ; then
    TEMP="${FILE%%.*}.tmp"
    echo $TEMP
    cp "$FILE" "$TEMP"
    while true ; do
        LINE="$(grep -m 1 '^.IMG\s' "$TEMP")"
        [ -n "$LINE" ] &&
            NEW_LINE="$(auto_pdfpic "$LINE")" &&
            sed -i "s@$LINE@$NEW_LINE@g" "$TEMP" ||
            break
    done
    FILE="$TEMP"
fi

sed "
s/Á/\\\['A\]/g;
s/É/\\\['E\]/g;
s/Í/\\\['I\]/g;
s/Ó/\\\['O\]/g;
s/Ú/\\\['U\]/g;
s/á/\\\['a\]/g;
s/é/\\\['e\]/g;
s/í/\\\['i\]/g;
s/ó/\\\['o\]/g;
s/ú/\\\['u\]/g;
" "$FILE" |
    soelim -I "$MAC" | refer -p "$BIB" | groff -mspdf -T pdf -U "$PRE"

rm -f "$TEMP"