#!/bin/bash

ECHOPREFIX=" => "
NULLPREFIX="    "

echo -e "$ECHOPREFIX Hello, this is \033[31mtexbox\033[0m"

if test "$(ls -A /tex)"; then
    # Directory not empty - user mounted directory \o/
    if [ -z "$TARGET" ]; then
        # target unset.
        TARGET="*.tex"
    fi

    # Build in build dir
    BUILD=$(date | sha256sum | cut -f1 -d' ')
    mkdir $BUILD
    cd $BUILD

    echo "$ECHOPREFIX Targetting $TARGET"

    # Build the PDF
    texi2pdf ../$TARGET

    if [ "$?" -eq "0" ]; then
        echo "$ECHOPREFIX Created the PDF!"
        echo "$NULLPREFIX Here are the results:"
        ls ../$BUILD/*.pdf
    else
        echo "$ECHOPREFIX Build failed."
        echo "$NULLPREFIX Have a look at the logs:"
        ls ../$BUILD/*.log
    fi

    cd ..

    # Delete old symlink
    rm ./current 2>/dev/null

    # Set 'current' symlink
    ln -sf $BUILD ./current
else
    # Directory is empty
    echo "$ECHOPREFIX Please mount your directory to /tex"
    echo "$NULLPREFIX See you soon."
fi

