#!/bin/sh
# Auto-configure Citizen CX-02 photo printer in CUPS.
# Called by udev when the printer is plugged in, and once during package install.
set -eu

QUEUE_NAME="CitizenCX02"
DRIVER="gutenprint.5.3://citizen-cx-02/expert"

# Check if queue already exists
if lpstat -p "$QUEUE_NAME" >/dev/null 2>&1; then
    exit 0
fi

# Unload usblp so gutenprint's libusb backend can access the CX-02.
# This is done here (not globally) because order kiosks need usblp for
# their USB-to-parallel thermal receipt printers.
if lsmod | grep -q usblp; then
    rmmod usblp 2>/dev/null || true
fi

# Wait briefly for the device to settle (udev context)
sleep 2

# Discover the device URI
DEVICE_URI=$(lpinfo -v 2>/dev/null | grep "gutenprint53+usb://citizen-cx-02" | awk '{print $2}' | head -1)

if [ -z "$DEVICE_URI" ]; then
    # Fallback: try direct USB URI
    DEVICE_URI=$(lpinfo -v 2>/dev/null | grep "usb://Citizen" | awk '{print $2}' | head -1)
fi

if [ -z "$DEVICE_URI" ]; then
    logger -t mymo-client-setup-cx02 "Could not find Citizen CX-02 device URI"
    exit 1
fi

# Create the CUPS queue
lpadmin -p "$QUEUE_NAME" \
    -v "$DEVICE_URI" \
    -m "$DRIVER" \
    -E \
    -o PageSize=w288h432 \
    -o StpImageType=Photo \
    -o StpLaminate=Glossy

logger -t mymo-client-setup-cx02 "Created CUPS queue $QUEUE_NAME with URI $DEVICE_URI"
