#!/bin/bash

ECHOPREFIX=" => "
NULLPREFIX="    "

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

if ! test "$(ls -A /tex)"; then
    # Directory is empty
    echo "$ECHOPREFIX Please mount your directory to /tex"
    echo "$NULLPREFIX See you soon."
    exit 1
fi

# Directory not empty - user mounted directory \o/
if [ -z "$TARGET" ]; then
    # target unset.
    TARGET="$(find /tex -iname '*.tex' | head --lines 1)"
fi

# Build in build dir
BUILD="$(mktemp --directory)"
cd "$BUILD"

echo "$ECHOPREFIX Targetting $TARGET"

# Build the PDF
texi2pdf $TARGET

# Relocate resulting PDF
find "$BUILD" -iname "*.pdf" -exec chmod --silent --reference=$TARGET {} \; -exec chown --silent --reference=$TARGET -R $BUILD {} \; -exec mv {} /tex \;
