#!/bin/bash
set -euo pipefail

# Color definitions
BOLD='\033[1m'
RED='\033[31m'
BLUE='\033[34m'
RESET='\033[0m'

# Ensure a file parameter is passed
if [[ $# -lt 1 ]]; then
    echo -e "${BOLD}${RED}Error${RESET}${RED}: No .tex file provided.${RESET}"
    echo "Usage: $0 <file.tex>"
    exit 1
fi

FILE="$1"

# append .tex file extension, iff not already passed
[[ "$FILE" != *.tex ]] && FILE="${FILE}.tex"

# Check that the file exists
if [[ ! -f "$FILE" ]]; then
    echo -e "${BOLD}${RED}Error${RESET}${RED}: File '$FILE' not found.${RESET}"
    exit 1
fi

# Detect active \usepackage{fontspec} (ignore commented lines)
if grep -Eq '^[^%]*\\usepackage\{fontspec\}' "$FILE"; then
    echo -e "${BLUE}Detected fontspec → Using XeLaTeX${RESET}"
    xelatex -synctex=1 -interaction=nonstopmode -file-line-error "$FILE"
else
    echo -e "${BLUE}No active fontspec → Using pdfLaTeX${RESET}"
    pdflatex -synctex=1 -interaction=nonstopmode -file-line-error "$FILE"
fi
