#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check for required commands
echo -e "${YELLOW}Checking requirements...${NC}"

# Check for pandoc
if ! command -v pandoc &> /dev/null; then
    echo -e "${RED}Error: pandoc is not installed.${NC}"
    echo "Please install pandoc first. On Arch Linux, run: sudo pacman -S pandoc"
    exit 1
fi

# Check for xelatex
if ! command -v xelatex &> /dev/null; then
    echo -e "${RED}Error: xelatex is not installed.${NC}"
    echo "Please install xelatex first. On Arch Linux, run: sudo pacman -S texlive-most"
    exit 1
fi

# Check if the format file exists and try to initialize if not
if ! kpsewhich xelatex.fmt &> /dev/null; then
    echo -e "${YELLOW}xelatex.fmt not found. Attempting to initialize TeX formats...${NC}"
    echo -e "This may take a moment..."
    
    # Try to initialize the formats
    if command -v fmtutil-sys &> /dev/null; then
        sudo fmtutil-sys --all
    elif command -v fmtutil &> /dev/null; then
        fmtutil --user --all
    else
        echo -e "${RED}Cannot find fmtutil. Please run 'sudo fmtutil-sys --all' manually.${NC}"
        exit 1
    fi
    
    # Check again if initialization was successful
    if ! kpsewhich xelatex.fmt &> /dev/null; then
        echo -e "${RED}Failed to initialize xelatex.fmt.${NC}"
        echo "Try running the following commands manually:"
        echo "  sudo pacman -S texlive-bin texlive-core texlive-latexextra"
        echo "  sudo fmtutil-sys --all"
        exit 1
    fi
fi

echo -e "${GREEN}All requirements satisfied!${NC}"
echo -e "${YELLOW}Generating resume PDF...${NC}"

# Generate resume PDF using pandoc
pandoc resume.md \
  --template=resume-template.tex \
  --pdf-engine=xelatex \
  -o resume.pdf

# Check if PDF was generated successfully
if [ -f "resume.pdf" ]; then
    echo -e "${GREEN}Resume PDF generated successfully as resume.pdf${NC}"
    # Get file size in human-readable format
    FILE_SIZE=$(du -h resume.pdf | cut -f1)
    echo -e "File size: ${YELLOW}${FILE_SIZE}${NC}"
    echo -e "You can now view your resume with: ${YELLOW}xdg-open resume.pdf${NC}"
else
    echo -e "${RED}Error: Failed to generate resume.pdf${NC}"
    echo -e "You may need additional LaTeX packages. Try installing:"
    echo -e "  sudo pacman -S texlive-fontsextra texlive-fontutils"
    exit 1
fi 