#!/bin/bash

# Define image name
IMAGE_NAME="pandoc-report-generator"
PDF_MAKE_DIR="." # Path to your Dockerfile and generate_reports.sh
LABS_DIR="../.."         # Path to your labs directory
WORKING_DIRECTORY=$(dirname "$0")

echo "--- Debug Info ---"
echo "Directory name: $(dirname "$0")"
echo "Current Working Directory: ${WORKING_DIRECTORY}"
echo "Image Name (variable): '$IMAGE_NAME'"
echo "PDF Make Directory (variable): '$PDF_MAKE_DIR'"
echo "Labs Directory (variable): '$LABS_DIR'"
echo "Absolute Labs Mount Path: '${WORKING_DIRECTORY}/$LABS_DIR'"
echo "--------------------"

echo "--- Building Docker image: $IMAGE_NAME ---"
# Build the Docker image from the pdf_make directory
docker build -t "$IMAGE_NAME" "$WORKING_DIRECTORY/$PDF_MAKE_DIR"
BUILD_STATUS=$?
echo "Build command exited with status: $BUILD_STATUS"

if [ $BUILD_STATUS -ne 0 ]; then
    echo "ERROR: Docker image build failed. Exiting."
    exit 1
fi

echo "--- Running report generation inside Docker container ---"
# This single-line docker run command is the most robust way to avoid shell parsing issues.
# It explicitly sets the entrypoint and mounts the /labs directory.
docker run --rm --entrypoint /bin/sh -v "${WORKING_DIRECTORY}/$LABS_DIR:/labs" "$IMAGE_NAME" /app/generate_reports.sh

RUN_STATUS=$?
echo "Run command exited with status: $RUN_STATUS"

if [ $RUN_STATUS -ne 0 ]; then
    echo "ERROR: Report generation failed inside Docker container."
    exit 1
fi

echo "--- All operations completed successfully. ---"

# --- New Step: Verify Output on Host ---
echo "--- Verifying generated PDFs on host ---"
find "${WORKING_DIRECTORY}/$LABS_DIR" -type f -name "LAB-REPORT.pdf"

if [ $? -eq 0 ]; then
    echo "PDFs should now be available in your '$LABS_DIR' directory."
else
    echo "No PDFs found or an error occurred during verification."
fi
