#!/bin/bash
# PrintControl CUPS backend — wraps ipp/socket/usb/parallel after a local quota decide.
# Device URI examples:
#   printcontrol:ipp://192.168.1.50/ipp/print
#   printcontrol:socket://192.168.1.50:9100
#   printcontrol:usb://Kyocera/ECOSYS?serial=ABC
#
# For socket:// (raw 9100) behind PrintControlGateway, injects SPAT:<token>\n
# when decide returns a capability ticket.
#
# CUPS invokes backends as: backend job-id user title copies options [file]
set -euo pipefail

DECIDE_URL="${PRINTCONTROL_DECIDE_URL:-http://127.0.0.1:5067/decide}"
BACKEND_DIR="${CUPS_SERVERBIN:-/usr/lib/cups}/backend"

if [ $# -eq 0 ]; then
  # Discovery — advertise that we exist (no device enumeration)
  echo 'direct printcontrol "PrintControl Quota Gate" "PrintControl Cloud (Extreme Technology)"'
  exit 0
fi

JOB_ID="${1:-}"
USER_NAME="${2:-}"
TITLE="${3:-document}"
COPIES="${4:-1}"
OPTIONS="${5:-}"
FILE="${6:-}"

DEVICE_URI="${DEVICE_URI:-}"
if [ -z "$DEVICE_URI" ]; then
  echo "ERROR: DEVICE_URI not set" >&2
  exit 1
fi

# Strip scheme printcontrol: → real backend URI
REAL_URI="${DEVICE_URI#printcontrol:}"
case "$REAL_URI" in
  ipp://*|ipps://*) INNER=ipp ;;
  socket://*)       INNER=socket ;;
  usb://*)          INNER=usb ;;
  parallel:*)       INNER=parallel ;;
  file:*)           INNER=file ;;
  http://*|https://*) INNER=ipp ;;
  *)
    echo "ERROR: unsupported printcontrol URI: $DEVICE_URI" >&2
    exit 1
    ;;
esac

INNER_BIN="$BACKEND_DIR/$INNER"
if [ ! -x "$INNER_BIN" ]; then
  echo "ERROR: CUPS backend not found: $INNER_BIN" >&2
  exit 1
fi

PAGES=1
# Prefer copies from CUPS; color / duplex hints from options
COLOR=false
DUPLEX=false
echo "$OPTIONS" | grep -qi 'ColorModel=RGB\|print-color-mode=color\|CNIJGrayScale=0' && COLOR=true || true
echo "$OPTIONS" | grep -qi 'sides=two-sided\|Duplex=Duplex' && DUPLEX=true || true
if [ -n "${FILE:-}" ] && command -v pdfinfo >/dev/null 2>&1; then
  P=$(pdfinfo "$FILE" 2>/dev/null | awk '/^Pages:/ {print $2}')
  if [ -n "${P:-}" ] && [ "$P" -gt 0 ] 2>/dev/null; then
    PAGES=$((P * COPIES))
  else
    PAGES=$COPIES
  fi
else
  PAGES=$COPIES
fi

PRINTER_NAME="${PRINTER:-cups}"
PAYLOAD=$(printf '{"userName":%s,"printerName":%s,"documentName":%s,"pageCount":%s,"isColor":%s,"isDuplex":%s,"report":true}' \
  "$(printf '%s' "$USER_NAME" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))')" \
  "$(printf '%s' "$PRINTER_NAME" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))')" \
  "$(printf '%s' "$TITLE" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))')" \
  "$PAGES" \
  "$COLOR" \
  "$DUPLEX")

DECISION_JSON=$(curl -sS --max-time 8 -X POST -H 'Content-Type: application/json' -d "$PAYLOAD" "$DECIDE_URL" || echo '{"decision":"hold","reason":"decide_unreachable"}')
DECISION=$(printf '%s' "$DECISION_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("decision","block"))' 2>/dev/null || echo block)
REASON=$(printf '%s' "$DECISION_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("reason",""))' 2>/dev/null || true)
SPAT_TOKEN=$(printf '%s' "$DECISION_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("spat") or "")' 2>/dev/null || true)
FORCE_DUPLEX=$(printf '%s' "$DECISION_JSON" | python3 -c 'import json,sys; print("true" if json.load(sys.stdin).get("forceDuplex") else "")' 2>/dev/null || true)
FORCE_BW=$(printf '%s' "$DECISION_JSON" | python3 -c 'import json,sys; print("true" if json.load(sys.stdin).get("forceBw") else "")' 2>/dev/null || true)

case "$DECISION" in
  allow)
    ;;
  hold)
    echo "ERROR: PrintControl hold ($REASON) — release from cloud portal / Find-Me" >&2
    exit 1
    ;;
  *)
    echo "ERROR: PrintControl blocked ($REASON)" >&2
    exit 1
    ;;
esac

# Policy Pack transforms (enforce only — shadow never sets force* flags)
if [ "$FORCE_DUPLEX" = "true" ]; then
  OPTIONS="${OPTIONS:+$OPTIONS }sides=two-sided-long-edge"
fi
if [ "$FORCE_BW" = "true" ]; then
  OPTIONS="${OPTIONS:+$OPTIONS }print-color-mode=monochrome ColorModel=Gray"
fi

export DEVICE_URI="$REAL_URI"

# Raw :9100 behind PrintControlGateway — prepend SPAT ticket then stream job.
if [ "$INNER" = "socket" ] && [ -n "${SPAT_TOKEN:-}" ]; then
  if [ -n "${FILE:-}" ]; then
    { printf 'SPAT:%s\n' "$SPAT_TOKEN"; cat -- "$FILE"; } | "$INNER_BIN" "$JOB_ID" "$USER_NAME" "$TITLE" "$COPIES" "$OPTIONS"
  else
    { printf 'SPAT:%s\n' "$SPAT_TOKEN"; cat; } | "$INNER_BIN" "$JOB_ID" "$USER_NAME" "$TITLE" "$COPIES" "$OPTIONS"
  fi
  exit $?
fi

if [ -n "${FILE:-}" ]; then
  exec "$INNER_BIN" "$JOB_ID" "$USER_NAME" "$TITLE" "$COPIES" "$OPTIONS" "$FILE"
else
  exec "$INNER_BIN" "$JOB_ID" "$USER_NAME" "$TITLE" "$COPIES" "$OPTIONS"
fi
