#!/bin/sh -eu
# pdf-lighten-black IN.pdf [OUT.pdf] [GREY]
#
# Produce a copy of IN.pdf in which all *vector* pure black is replaced by a
# dark grey (default 10% = #1a1a1a). Intended for printing on fabric, where
# solid black ink bleeds out, making QR codes hard to scan and text fuzzy.
#
# Works on the PDF content streams directly (qpdf QDF round-trip), so text
# stays text and vector graphics stay vector -- nothing is rasterized and the
# file works at any print resolution. Colors inside embedded raster images
# (e.g. screenshots) are not touched.
#
# GREY is the target grey level in [0,1) per RGB channel (0.10 = 10% = #1a1a1a).

in=$1
out=${2:-${in%.pdf}_fabric.pdf}
grey=${3:-0.10}

k=$(awk -v g="$grey" 'BEGIN { printf "%.4g", 1 - g }')

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

# QDF mode writes an editable, uncompressed PDF whose stream lengths can be
# repaired by fix-qdf after editing.
qpdf --qdf --object-streams=disable "$in" "$tmpdir/in.qdf"

# Rewrite the color-setting operators for pure black:
#   `0 0 0 rg/RG` (DeviceRGB), `0 g/G` (DeviceGray), `0 0 0 sc/scn` variants,
#   and `0 0 0 1 k/K` (DeviceCMYK, mapped to (1-GREY) K).
# The lookarounds keep numbers like `10 g` or names like `/GS0 gs` intact.
perl -pe "
  s/(?<![\\d.])0 0 0 (rg|RG|scn|sc|SCN|SC)(?![\\w])/$grey $grey $grey \$1/g;
  s/(?<![\\d.])0 (g|G)(?![\\w])/$grey \$1/g;
  s/(?<![\\d.])0 0 0 1 (k|K)(?![\\w])/0 0 0 $k \$1/g;
" "$tmpdir/in.qdf" | fix-qdf > "$tmpdir/grey.qdf"

# Rewrite as a normal, compressed PDF.
qpdf "$tmpdir/grey.qdf" "$out"

echo "pdf-lighten-black: wrote $out (black -> ${grey} grey)" >&2
