#!/bin/sh
# CUPS backend "ribbon-pdf": the "Print to Red Ribbon" queue sends its jobs here.
# It saves each job as a PDF in the printing user's Red Ribbon inbox
# (~/.local/share/ribbon/inbox), which a running Red Ribbon watches and opens as a
# new, unsaved document (docs/printer.md). Installed by install.sh into CUPS's
# backend folder, where it runs as root, so the job's owner is looked up and
# given the file.
#
# CUPS calls it as: ribbon-pdf job-id user title copies options [file]
# (no arguments: device discovery). RIBBON_INBOX overrides the folder (tests).
#
# The job must already be a PDF: GTK, Qt, Firefox, Chrome and LibreOffice send
# PDF to a raw queue. A PostScript job is converted with ps2pdf when the
# machine has Ghostscript; Red Ribbon doesn't ship one (AGPL).

if [ $# -eq 0 ]; then
    echo 'direct ribbon-pdf "Unknown" "Print to Red Ribbon"'
    exit 0
fi
if [ $# -lt 5 ]; then
    echo "Usage: ribbon-pdf job-id user title copies options [file]" >&2
    exit 1
fi

job="$1"
user="$2"
title="$3"
file="$6"

inbox="$RIBBON_INBOX"
if [ -z "$inbox" ]; then
    home=$(getent passwd "$user" | cut -d: -f6)
    if [ -z "$home" ]; then
        echo "ERROR: ribbon-pdf: no home folder for $user" >&2
        exit 1
    fi
    inbox="$home/.local/share/ribbon/inbox"
fi
mkdir -p "$inbox" || { echo "ERROR: ribbon-pdf: can't create $inbox" >&2; exit 1; }

# Hidden while being written: the watcher ignores names starting with a dot.
tmp=$(mktemp "$inbox/.job-XXXXXX") || { echo "ERROR: ribbon-pdf: can't write in $inbox" >&2; exit 1; }
trap 'rm -f "$tmp" "$tmp.pdf"' EXIT
if [ -n "$file" ]; then
    cat "$file" >"$tmp"
else
    cat >"$tmp"
fi

case "$(head -c 5 "$tmp")" in
    %PDF-) ;;
    %!*)
        # Ghostscript's own messages would land before the ERROR: line CUPS reads.
        if command -v ps2pdf >/dev/null 2>&1 && ps2pdf "$tmp" "$tmp.pdf" >/dev/null 2>&1; then
            mv "$tmp.pdf" "$tmp"
        else
            rm -f "$tmp.pdf"
            echo "ERROR: ribbon-pdf: the job is PostScript and couldn't be converted (install Ghostscript's ps2pdf)" >&2
            exit 1
        fi
        ;;
    *)
        echo "ERROR: ribbon-pdf: the job isn't a PDF" >&2
        exit 1
        ;;
esac

name=$(printf '%s' "$title" | tr -c 'A-Za-z0-9._ -' '_' | cut -c1-60)
[ -n "$name" ] || name="Printed"
target="$inbox/$name-$job.pdf"
mv "$tmp" "$target"
chmod 644 "$target"
if [ "$(id -u)" = 0 ]; then
    chown "$user" "$inbox" "$target" 2>/dev/null
fi
echo "INFO: ribbon-pdf: saved $target" >&2
exit 0
