#!/bin/bash

# Check if a file argument is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <file-to-convert>"
    exit 1
fi

# Assign the file argument to a variable
FILE_TO_CONVERT=$1
FILE_NAME=$(basename "$FILE_TO_CONVERT")

# Define the Gotenberg Docker image
GOTENBERG_IMAGE="gotenberg/gotenberg:8"

# Start the Gotenberg Docker container in the background
docker run --rm -d -p 3000:3000 --name gotenberg $GOTENBERG_IMAGE

# Function to stop the Docker container
function stop_container {
    docker stop gotenberg
}

# Register the stop_container function to be called on script exit
trap stop_container EXIT

# Wait for a moment to ensure that the container is up and running
sleep 3

# Determine the correct API endpoint based on the file extension
EXTENSION="${FILE_TO_CONVERT##*.}"
API_ENDPOINT="/forms/libreoffice/convert"

# Special handling for HTML files to use Chromium conversion
if [ "$EXTENSION" == "html" ]; then
    API_ENDPOINT="/forms/chromium/convert/html"
    # Ensure the HTML file is named index.html
    if [ "$FILE_NAME" != "index.html" ]; then
        echo "Renaming $FILE_NAME to index.html for conversion"
        cp "$FILE_TO_CONVERT" "/tmp/index.html"
        FILE_TO_CONVERT="/tmp/index.html"
    fi
fi

# Convert the file to PDF using the Gotenberg API
curl --request POST \
     --url http://localhost:3000$API_ENDPOINT \
     --header 'Content-Type: multipart/form-data' \
     --form files=@"$FILE_TO_CONVERT" \
     -o converted.pdf

# Check if the conversion was successful
if [ ! -f converted.pdf ]; then
    echo "Failed to convert the file to PDF."
    exit 3
fi

# Display the PDF with Evince
evince converted.pdf &
