#!/bin/bash

REAL="/usr/lib/cups/filter/rastertokpsl.real"

# Kyocera rastertokpsl uses the following arguments:
# $1 printer
# $2 job-id
# $3 title
# $4 copies
# $5 options

if [ "$#" -ne 5 ]; then
    echo "ERROR: rastertokpsl wrapper: expected 5 arguments, got $#" >&2
    exit 1
fi

printer="$1"
job_id="$2"
title="$3"
copies="$4"
options="$5"

# Convert the title to ASCII, remove unsupported characters,
# and keep only the last 20 alphanumeric characters.
safe_title="$(
    printf '%s' "$title" |
    iconv -f UTF-8 -t ASCII//TRANSLIT 2>/dev/null |
    LC_ALL=C tr -cd 'A-Za-z0-9' |
    tail -c 20
)"

[ -n "$safe_title" ] || safe_title="print-job"

# Pass the raster data through stdin.
exec "$REAL" \
    "$printer" \
    "$job_id" \
    "$safe_title" \
    "$copies" \
    "$options"
