#!/bin/bash

# Pandoc Markdown to PDF conversion script
# Usage: ./convert.sh <input_file> <output_file>

# Check if correct number of arguments provided
if [ $# -ne 2 ]; then
  echo "Usage: $0 <input_file> <output_file>"
  echo "Example: $0 ../Time\ Table.md ../Time\ Table.pdf"
  exit 1
fi

INPUT_FILE="$1"
OUTPUT_FILE="$2"

# Check if input file exists
if [ ! -f "$INPUT_FILE" ]; then
  echo "Error: Input file '$INPUT_FILE' not found"
  exit 1
fi

# Get the directory where the script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Convert markdown to PDF
pandoc "$INPUT_FILE" \
  -f markdown+wikilinks_title_after_pipe \
  -t html \
  -c "$SCRIPT_DIR/print.css" \
  -s \
  -M title="Time Table" \
  --lua-filter="$SCRIPT_DIR/image-filter.lua" \
  --pdf-engine=wkhtmltopdf \
  --pdf-engine-opt=--footer-center \
  --pdf-engine-opt="Author: Phil Keier - $(date +'%A, %d %B %Y - %H:%M')" \
  --pdf-engine-opt=--footer-font-size \
  --pdf-engine-opt=10 \
  -o "$OUTPUT_FILE"

# Check if conversion was successful
if [ $? -eq 0 ]; then
  echo "✓ PDF successfully created: $OUTPUT_FILE"
  tdf "$OUTPUT_FILE" 
  exit 0
else
  echo "✗ Error during PDF conversion"
  exit 1
fi
