#!/bin/bash

# Check if an argument is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

# Try to change into the directory, exit on failure
cd "$1" || { echo "Error: Cannot access directory '$1'"; exit 1; }

# Enable nullglob: if no pdfs exist, the loop won't run once with "*.pdf"
shopt -s nullglob

for file in *.pdf; do
    # Rotate to a temporary file
    if qpdf --rotate=+180 "$file" "temp_rotated.pdf"; then
        mv "temp_rotated.pdf" "$file"
        echo "Rotated: $file"
    else
        echo "Error processing: $file"
        # Clean up temp file if pdftk failed but created garbage
        [ -f "temp_rotated.pdf" ] && rm "temp_rotated.pdf"
    fi
done
