#!/bin/bash
# IMG2Print, print an Image file directly using img2pdf and lp.
# Concept and testing by Glen MacArthur, coded by Google Gemini 3.

ICON=/usr/local/share/icons/custom/print_img.png
IMAGE=/usr/local/share/icons/custom/print_img-app.png

if [ -z "$1" ]; then
    yad --error --width=400 --text="No image file selected." --window-icon="$ICON" --center
    exit 1
fi

PRINTER=$(lpstat -d | cut -d':' -f2 | xargs)

if [ -z "$PRINTER" ]; then
    yad --error --width=400 --text="<b>No Default Printer Found!</b>" --window-icon="$ICON" --center
    exit 1
fi

# --- 1. CLEAN ORIENTATION DIALOG ---
YAD_OUT=$(yad --form --title="Print Options" \
    --window-icon="$ICON" \
    --image="$IMAGE" \
    --width=600 --center \
    --field="File to Print:RO" "$(basename "$1")" \
    --field="Orientation:CB" "Landscape!Portrait" \
    --field="":LBL "" \
    --field="<b>Important Printing Note:</b>:LBL" "" \
    --field="This tool prints at 100% native size based on embedded DPI.:LBL" "" \
    --field="It will NOT stretch, distort, or scale your image to fit the page.:LBL" "")

[[ $? -ne 0 ]] && exit 0

SELECTION=$(echo "$YAD_OUT" | cut -d'|' -f2)

TEMP_PDF=$(mktemp /tmp/print_XXXXXX.pdf)

# --- 2. GENERATE GEOMETRY-ENFORCED PDF ---
img2pdf "$1" -o "$TEMP_PDF"

# --- 3. DIRECT CUPS PRINTING ---
if [ "$SELECTION" == "Landscape" ]; then
    # -o landscape tells CUPS to rotate its hardware coordinate grid
    # -o fit-to-page is intentionally omitted to prevent scaling distortion
    lp -d "$PRINTER" -o landscape -o position=center "$TEMP_PDF"
else
    lp -d "$PRINTER" -o position=center "$TEMP_PDF"
fi

# Extract the clean filename safely outside of YAD
FILENAME=$(basename "$1")

# Clean, self-closing status dialog
yad --form --undecorated \
    --window-icon="$ICON" \
    --image="$IMAGE" \
    --width=450 --center --no-buttons --timeout=3 \
    --field="<b>Sending to Printer...</b>:LBL" "" \
    --field="<b>File:</b> $FILENAME:LBL" "" \
    --field="Destination: <b>$PRINTER</b> ($SELECTION):LBL" ""

# Safe background cleanup delay
(sleep 10 && rm -f "$TEMP_PDF") &