#!/bin/sh
# Windows' printers made again from CUPS's, by the Windows system (SYSTEM),
# when CUPS's printers change (sg-printers-refresh.path).
#
# The machine's printers are in HKLM, which a standard user may not write:
# a printer added to CUPS during a session -- a DYMO LabelWriter plugged in,
# its queue made by sg-dymo-queue -- became a Windows printer for no one
# (wine-sg 0873 reloads them in the user's next program, and AddPrinter is
# refused there: "can't create driver ...: 5"). Here SYSTEM loads winspool
# (wmic over Win32_Printer); wine-sg sees that CUPS's printers changed since
# SYSTEM last made them and makes them again, for every user. Nothing to do
# while the machine's wineserver is not running: it loads them when it starts.
#
# SPDX-License-Identifier: AGPL-3.0-or-later
set -u
SG_LIB="${SG_LIB:-/usr/lib/stained-glass}"
# shellcheck source=lib/sg-common.sh
. "$SG_LIB/sg-common.sh"
# Only while someone is signed in: never on a live boot (Setup), before the
# first-boot setup is done, or with only the login screen up -- a SYSTEM
# Windows program then took the keys from Setup and the first-boot setup
# (0.1.0-118). Printers present at boot are loaded by the Windows system as
# it starts; this is for those added during a session.
OOBE_PENDING="${SG_OOBE_PENDING:-/etc/stained-glass/oobe.pending}"
CMDLINE="${SG_PROC_CMDLINE:-/proc/cmdline}"
RUN_USER="${SG_RUN_USER:-/run/user}"
[ -e "$OOBE_PENDING" ] && { echo "sg-printers-refresh: first-boot setup pending"; exit 0; }
grep -q 'systemd.volatile=overlay' "$CMDLINE" 2>/dev/null && { echo "sg-printers-refresh: live boot"; exit 0; }
ls "$RUN_USER"/*/sg-session.env >/dev/null 2>&1 || { echo "sg-printers-refresh: no one is signed in"; exit 0; }
sg_machine_wineserver_up || { echo "sg-printers-refresh: the machine wineserver is not running"; exit 0; }
# And in the services' window station, as the SCM's programs are, never
# the interactive one (WinSta0) where the login screen, Setup and the
# sessions' desktops are: there, with explorer.exe disabled, it took
# WinSta0's Default desktop as the login screen started on it, and the login
# screen waited on that desktop for good (release s9's first boot,
# 2026-10-05).
out=$(timeout 120 runuser -u "$SG_SYSTEM_USER" -- sh -c \
    '. /usr/lib/stained-glass/sg-common.sh; sg_wine_env; unset DISPLAY WAYLAND_DISPLAY
     SG_WINSTATION="__wineservice_winstation\Default"; export SG_WINSTATION
     export WINEDEBUG=-all WINEDLLOVERRIDES="winemenubuilder.exe=d;explorer.exe=d"
     wine wmic path Win32_Printer get Name
     # every printer'"'"'s driver readied as SYSTEM, point-and-print style: a
     # standard user may not write it, so a queue no administrator opened had
     # no driver for them; and a maker'"'"'s staged package installed (wine-sg 0922)
     wine splwow64.exe drivers >/dev/null 2>&1' 2>/dev/null | tr -d '\r')
echo "sg-printers-refresh: printers now: $(printf '%s\n' "$out" | sed '1d; s/[[:space:]]*$//; /^$/d' | paste -sd, -)"
exit 0
