#!/usr/bin/env sh

# This script will compile or run another finishing operation on a document. I
# have this script run via vim.
# Compiles .tex. groff (.mom, .ms), .rmd, .md.  Opens .sent files as sent
# presentations.  Runs scripts based on extention or shebang
# by lukesmithxyz, checkout github.com/lukesmithxyz/voidrice

file=$(readlink -f "$1")
dir=$(dirname "$file")
base="${file%.*}"
basenodir="${1%.*}"
vipercmd="carbon" #"silicon"

cd "$dir" || exit

has_python_version() {
    dir="$PWD"
    while [ "$dir" != "/" ]; do
        if [ -f "$dir/.python-version" ] || [ -f "$dir/pyproject.toml" ]; then
            return 0
        fi
        dir=$(dirname "$dir")
    done
    return 1
}

textype() {
    command="pdflatex --shell-escape"
    # Detect XeLaTeX from the first 15 lines. Supported forms include:
    #   % !TeX program = xelatex
    #   % xelatex
    # and packages which require or commonly imply XeLaTeX.
    if sed -n '1,15p' "$file" | grep -Eiq \
        '(^%+[[:space:]]*!tex[[:space:]]+program[[:space:]]*=[[:space:]]*xelatex)|(^%+[[:space:]]*xelatex[[:space:]]*$)|(\\usepackage[^}]*\{(fontspec|unicode-math|mathspec)\})'; then
        command="xelatex"
    fi

    $command --output-directory="$dir" "$base" || return 1

    if grep -iq '\\addbibresource' "$file"; then
        biber --input-directory "$dir" "$base" || return 1
        $command --output-directory="$dir" "$base" || return 1
    fi

    if grep -iq '\\makeglossaries' "$file"; then
        makeglossaries "$basenodir" || return 1
        $command --output-directory="$dir" "$base" || return 1
    fi

    return 0
}

case "$file" in
*\.[0-9]) refer -PS -e "$file" | groff -mandoc -T pdf >"$base".pdf ;;
*\.bash) bash "$file" ;;
*\.go) go run "$file" ;;
*\.lua) lua "$file" ;;
*\.md) pandoc "$file" --pdf-engine=xelatex -o "$base".pdf ;;
*\.mom) refer -PS -e "$file" | groff -mom -kept -T pdf >"$base".pdf ;;
*\.ms) refer -PS -e "$file" | groff -me -ms -kept -T pdf >"$base".pdf ;;
*\.py)
    if has_python_version; then
        uv run python "$file"
    else
        python3 "$file"
    fi
    ;;
*\.rmd) echo "require(rmarkdown); render('$file')" | R -q --vanilla ;;
*\.sent) setsid sent "$file" 2>/dev/null & ;;
*config.h) sudo make install ;;
*\.c) if [ -f Makefile ]; then make run; else cc "$file" -o "$base" && "$base"; fi ;;
*\.java) java "$file" ;;
*\.js) node "$file" ;;
*\.m) octave -qW "$file" ;;
*\.nim) nim c -r -d:noColors "$file" ;;
*\.r | *\.R) Rscript "$file" ;;
*\.rs) (cd "$dir" && cargo locate-project >/dev/null 2>&1) &&
    (cd "$(dirname "$(cd "$dir" && cargo locate-project --message-format plain)")" && cargo run) ||
    (rustc "$file" && "./$(basename "${file%.rs}")") ;;
*\.sh) dash "$file" ;;
*\.smt2) z3 "$file" ;;
*\.tex) textype "$file" ;;
*\.vpr) $vipercmd "$file" ;;
*\.zsh) zsh "$file" ;;
*\.ly) lilypond "$file" ;;
*) sed 1q "$file" | grep "^#!/" | sed "s/^#!//" | xargs -r -I % "$file" ;;
esac
