#!/bin/sh
# ============================================================================
#  tspl — CUPS backend for TSPL/TSPL2 thermal label printers on Linux/ARM.
#
#  Drives ANY USB printer that speaks TSPL — reference-tested on the HZD950-PRO,
#  and matches the common rebadges (Munbyn, iDPRT, HPRT, Beeprt, JADENS, Polono,
#  Xprinter, ...). Writes the (already-TSPL) job straight to the printer's usblp
#  character device, located by USB so it survives reboots / re-enumeration and
#  coexists with other USB printers — unlike the libusb "usb" backend, which
#  detaches usblp and causes a first-job-after-boot race.
#
#  Confirm your printer really speaks TSPL (prints nothing):
#     cat /sys/class/usbmisc/lp0/device/ieee1284_id
#  and look for TSPL in the CMD: / COMMAND SET: field (the HZD950-PRO reports
#  "COMMAND SET:TSPL"). A missing TSPL string is not a no: the XP-420B
#  advertises "CMD:CEZD" and drives fine.
#  (~!T also returns a model string per spec, but many clones are write-only
#  over USB, so don't trust a silent read.)
#
#  Device URI:
#     tspl://auto            the TSPL label printer (see auto-match below)
#     tspl://<usb-serial>    a specific unit by its USB serial
#     tspl://<vid>-<pid>     a specific USB id, e.g. tspl://2d37-83d7
#     tspl:///dev/usb/lp0    a specific device node
#
#  Write a USB id with a DASH. CUPS parses the ":pid" of tspl://<vid>:<pid>
#  as a port number and rejects the whole URI unless the pid happens to be
#  all digits — lpadmin refuses 0fe6:811e, 2d84:b528 and 2d37:83d7, while
#  20d1:7008 sails through. The colon form is still accepted here for the
#  ids where it works, so existing queues keep printing.
#
#  Auto-match: uses the printer whose USB id is a known TSPL id (KNOWN_IDS
#  below). If yours isn't auto-detected, the error lists the USB printers it
#  DID find — pin one with tspl://<vid>-<pid> or tspl:///dev/usb/lpN, and please
#  open an issue with the id so we can add it to auto-detect.
#
#  Maintained FOR FREE by Run The Wall. If it saved you time, try our free
#  Markdown editor:  https://constly.com
#  SPDX-License-Identifier: MIT
# ============================================================================

# Known TSPL-label USB ids — tspl://auto matches nothing else, and discovery
# mode advertises tspl://auto only when one of these is attached; any other
# printer has to be pinned by vid-pid, serial or node. NB: 0fe6:811e is a
# squatted "ICS Advent Parallel Adapter" id — a generic USB-parallel printer
# bridge also seen on unrelated ESC/POS receipt printers (Gainscha GP80, Geyi
# Q583P) — so auto-match can still pick a non-TSPL device on that id; pin by
# serial/node if you have both kinds.
#   09c6:0426  Beeprt/JADENS/Munbyn-ITPP941/Rollo OEM engine
#              (linux-hardware.org reports it as "Beeprt LabelPrinter")
#   20d1:7008  iDPRT SP410/SP420, HPRT SK41 (confirmed; same Hanin parent;
#              Polono unconfirmed)
#   0fe6:811e  HZD950-PRO / HERO (reference unit) on the shared bridge id
#   2d84:*     Zhuhai Poskey / Xprinter label printers
#              (b806 = Poskey DT-108B per usb.ids; b528 seen on XP-460B)
#   2d37:*     Zhuhai Poskey again — usb.ids registers the SAME company under
#              two vendor ids; 83d7 reported on an XP-420B. Wildcarded like
#              2d84 since every Poskey product seen so far is a label printer.
#   5958:0041  Yxwl OEM engine (FlashLabel Y43BT and other Y4xBT rebadges);
#              confirmed TSPL via direct write to /dev/usb/lp0
#   2e3c:5757  123inkt LW650XL PRO (USB strings "QIN LabelPrinter"; an
#              Aimo/Quyin OEM unit). NB: 2e3c is Artery's AT32 MCU vendor
#              id, not a printer maker's, and absent from usb.ids, so other
#              Quyin rebadges may well share it — keep it pinned to :5757,
#              never 2e3c:*. ieee1284_id says "CMD:XPP,XL", no TSPL string
#              (see the XP-420B note in the header); confirmed by direct
#              write to /dev/usb/lp0
KNOWN_IDS="09c6:0426 20d1:7008 0fe6:811e 2d84:* 2d37:* 5958:0041 2e3c:5757"

usb_attr() {   # $1 = usblp minor, $2 = sysfs attr
    sl=$(readlink -f "/sys/dev/char/180:$1" 2>/dev/null) || return
    d="$sl"
    while [ -n "$d" ] && [ "$d" != "/" ]; do
        if [ -f "$d/idVendor" ]; then cat "$d/$2" 2>/dev/null; return; fi
        d=$(dirname "$d")
    done
}
vidpid() { echo "$(usb_attr "$1" idVendor):$(usb_attr "$1" idProduct)"; }
is_known() {   # $1 = "vid:pid"
    # $k stays unquoted on purpose: entries such as "2d84:*" are glob patterns
    # matching a whole vendor, not literal strings. The subshell keeps
    # pathname expansion off while the list is split, or the shell would
    # first try each pattern against the CWD: cupsd only chdirs to / when it
    # daemonizes, so a hand-run cupsd -f (or a unit with its own
    # WorkingDirectory) leaves the backend in that directory, where a file
    # named 2d84:anything would replace the entry before case sees it.
    (
        set -f
        # shellcheck disable=SC2254
        for k in $KNOWN_IDS; do case "$1" in $k) exit 0 ;; esac; done
        exit 1
    )
}
# Where usblp nodes live. A function, not a variable, so that tests/backend.sh
# can point the scan at a scratch directory by overriding it the same way it
# overrides usb_attr - and so nothing in the environment can redirect it.
devdir() { echo /dev/usb; }

is_node() {    # $1 = path -> true only for a character device
    # -c, never -e. If the printer drops off the bus mid-job, its node
    # disappears, and the next write to that path CREATES A REGULAR FILE there.
    # An existence test then accepts the file forever after: the minor is taken
    # from the NAME, so sysfs still reports char 180:0's vid:pid once the
    # printer re-enumerates, is_known() matches, and the job is written into the
    # file. The redirect succeeds, the backend exits 0, and CUPS reports a
    # printed job that never reached the printer. Observed on an HZD950-PRO that
    # re-enumerated three times in an hour: five jobs silently filed into
    # /dev/usb/lp0 as a 270 KB regular file.
    #
    # Taking the minor from the name rather than the inode is left as is on
    # purpose: with -c in place the two can only disagree if something creates a
    # character device under a misleading name in this directory, and udev owns
    # it. Reading /sys/class/usbmisc/<name>/dev would close even that.
    [ -c "$1" ]
}

each_node() {  # -> "minor node" per usblp device
    d=$(devdir)
    for n in "$d"/lp*; do
        if is_node "$n"; then echo "${n##*lp} $n"; fi
    done
}

stale_nodes() {  # -> paths that look like nodes but are not character devices
    # Reported only when resolution has already failed. Warning from inside
    # each_node() instead would fire on every call, and the boot-settling loop
    # below calls it once per two-second iteration.
    d=$(devdir)
    for n in "$d"/lp*; do
        if [ -e "$n" ] && ! is_node "$n"; then echo "$n"; fi
    done
}

# Resolve target node. $1 = auto | serial | vid-pid | /dev/... . Echoes a node.
# Safe by default: "auto" only matches a KNOWN TSPL usb id, so it will not grab
# an unrelated printer such as a laser. Pin unknown units by vid-pid or node.
find_node() {
    want=$1
    case "$want" in /dev/*) is_node "$want" && echo "$want"; return ;; esac
    # Accept a USB id as vid-pid or vid:pid, in either case: sysfs reports
    # lowercase hex, and the dash spelling is the one CUPS lets through (see
    # the Device URI note in the header). A serial is compared as typed, so a
    # serial containing a dash still matches on the serial pass below.
    id=$(printf '%s' "$want" | tr 'A-Z-' 'a-z:')
    known=""
    while read -r m n; do
        [ -n "$m" ] || continue
        vp=$(vidpid "$m"); ser=$(usb_attr "$m" serial)
        case "$id" in
            ''|auto) is_known "$vp" && [ -z "$known" ] && known=$n ;;
            *)       [ "$vp" = "$id" ]    && { echo "$n"; return; }
                     [ "$ser" = "$want" ] && { echo "$n"; return; } ;;
        esac
    done <<EOF
$(each_node)
EOF
    case "$id" in ''|auto) [ -n "$known" ] && echo "$known" ;; esac
}

# --- discovery mode (no args) ---
if [ "$#" -eq 0 ]; then
    [ -n "$(find_node auto)" ] && \
      echo 'direct tspl://auto "Unknown" "TSPL label printer (Run The Wall driver)"'
    exit 0
fi

# --- print mode: job user title copies options [file] ---
echo "INFO: tspl — FREE Linux/Pi TSPL label-printer driver by Run The Wall. Support us: https://constly.com" 1>&2

WANT=${DEVICE_URI#tspl://}
WANT=${WANT#tspl:}
[ "$WANT" = "$DEVICE_URI" ] && WANT=auto        # bare / unknown -> auto

DEV=$(find_node "$WANT")
i=0
while [ -z "$DEV" ] && [ -z "$(each_node)" ] && [ "$i" -lt 30 ]; do   # boot settling
    echo "INFO: waiting for a USB printer to appear..." 1>&2
    sleep 2; i=$((i + 1)); DEV=$(find_node "$WANT")
done
if [ -z "$DEV" ]; then
    echo "ERROR: no matching TSPL label printer on USB (wanted: ${WANT:-auto})." 1>&2
    echo "ERROR: USB printers present:" 1>&2
    each_node | while read -r m n; do
        echo "ERROR:   $n  (usb $(vidpid "$m"), serial $(usb_attr "$m" serial))" 1>&2
    done
    stale=$(stale_nodes)
    if [ -n "$stale" ]; then
        echo "ERROR: stale files sit where device nodes belong. The printer dropped" 1>&2
        echo "ERROR: off USB and a write created these; remove them and replug it:" 1>&2
        echo "$stale" | while read -r f; do echo "ERROR:   $f" 1>&2; done
    fi
    echo "ERROR: pin one with tspl://<vid>-<pid> (dash, e.g. tspl://2d37-83d7)," 1>&2
    echo "ERROR: tspl://<usb-serial>, or tspl:///dev/usb/lpN" 1>&2
    exit 1
fi
echo "INFO: using TSPL printer at $DEV (usb $(vidpid "${DEV##*lp}"))" 1>&2

# Spool the whole job, then hand it to the printer in one burst. Do NOT
# stream at render speed: cheap TSPL firmwares (HZD950-PRO confirmed, by
# byte-capture A/B test) silently discard pages that arrive while the
# printer is already printing — a multi-page or multi-copy job trickling
# in pauses between pages loses everything after label 1. The same bytes
# written back-to-back print completely.
TMP=$(mktemp "${TMPDIR:-/tmp}/tspl-job.XXXXXX") || exit 1
trap 'rm -f "$TMP"' EXIT
if [ -n "$6" ]; then cat "$6" > "$TMP"; else cat > "$TMP"; fi
# Last line of defence: never write a job anywhere but a character device.
# Without this a stale regular file silently absorbs the job and reports success.
if ! is_node "$DEV"; then
    echo "ERROR: $DEV is not a character device - refusing to write." 1>&2
    echo "ERROR: remove the stale file and replug the printer, or pin the node." 1>&2
    exit 1
fi
cat "$TMP" > "$DEV" || exit $?
# The guard above and this redirect are two separate syscalls, and POSIX sh
# cannot open a file without O_CREAT. If the printer disappears in between, ">"
# creates a regular file, cat succeeds, and we would again report a print that
# never happened. Unpreventable, but detectable: re-check, and clear the file we
# just created so the next job is not resolved onto it.
if ! is_node "$DEV"; then
    echo "ERROR: $DEV stopped being a character device mid-write - the printer" 1>&2
    echo "ERROR: dropped off USB. This job was NOT printed." 1>&2
    [ -f "$DEV" ] && rm -f "$DEV"
    exit 1
fi
exit 0
