#!/bin/bash

echo "Starting report generation..."

# Navigate to the /labs directory within the container
# This is crucial because we're mounting the host's /labs into the container's /labs
cd /labs || { echo "Error: /labs directory not found in container. Exiting."; exit 1; }

# Find all directories prefixed with "lab-"
find . -maxdepth 1 -type d -name "lab-*" | while read lab_dir; do
    echo "Processing directory: $lab_dir"
    markdown_file="$lab_dir/LAB-REPORT.md"
    pdf_file="$lab_dir/LAB-REPORT.pdf"

    # Check if LAB-REPORT.md exists
    if [ -f "$markdown_file" ]; then
        echo "Found $markdown_file"
        # Check if LAB-REPORT.pdf does not exist
        if [ ! -f "$pdf_file" ]; then
            echo "LAB-REPORT.pdf not found. Generating PDF from markdown..."
            # Generate PDF using pandoc
            # Make sure 'pandoc' command is available in the image, which it is for pandoc/latex
            image_dir="$lab_dir"
            pandoc "$markdown_file" -s -o "$pdf_file" --pdf-engine=pdflatex --resource-path "$image_dir"

            if [ $? -eq 0 ]; then
                echo "Successfully generated $pdf_file"
            else
                echo "Error generating $pdf_file"
            fi
        else
            echo "LAB-REPORT.pdf already exists. Skipping generation."
        fi
    else
        echo "LAB-REPORT.md not found in $lab_dir. Skipping."
    fi
done

echo "Report generation complete."
