#!/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_uv_project() {
    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"
    (sed 5q "$file" | grep -i -q 'xelatex') && command="xelatex"
    $command --output-directory="$dir" "$base" &&
        grep -i addbibresource "$file" >/dev/null &&
        biber --input-directory "$dir" "$base" &&
        $command --output-directory="$dir" "$base" &&
        makeglossaries "$basenodir" &&
        $command --output-directory="$dir" "$base"
}

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_uv_project; 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
