#!/bin/sh
# Names whose folders zPrint's virtual printers save to on this Linux computer.
#
#   sudo zprint-owner NAME     Save into NAME's folders (~/Downloads/zPrint by default)
#   sudo zprint-owner --none   Offer no virtual printers; only share the CUPS printers
#   zprint-owner               Show who it is now
#
# The service runs as its own account and can't write into anyone's home folder, so it hands
# each job to a small agent that runs as the owner (zprint-agent, a systemd user service). This
# keeps that agent running from boot, even while the owner isn't logged in, with
# `loginctl enable-linger`. An "owner" in /var/lib/zprint/zprint.json takes precedence.
set -eu
DEFAULTS=/etc/default/zprintd

current() {
  sed -n 's/^ZPRINTD_OPTIONS=".*--owner \([^ "]*\).*"/\1/p' "$DEFAULTS" 2>/dev/null | tail -n 1
}

case "${1:-}" in
  "")
    owner="$(current)"
    if [ -n "$owner" ]; then echo "$owner"; else echo "No owner: zPrint shares the CUPS printers only."; fi
    exit 0 ;;
  -h|--help) sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
esac

if [ "$(id -u)" -ne 0 ]; then echo "Run it with sudo." >&2; exit 1; fi
touch "$DEFAULTS"
grep -q '^ZPRINTD_OPTIONS=' "$DEFAULTS" || echo 'ZPRINTD_OPTIONS=""' >> "$DEFAULTS"

if [ "$1" = "--none" ]; then
  sed -i 's/ *--owner [^ "]*//' "$DEFAULTS"
  systemctl restart zprintd.service
  echo "zPrint now offers no virtual printers."
  exit 0
fi

name="$1"
case "$name" in -*|*[!A-Za-z0-9._-]*) echo "\"$name\" is not an account name." >&2; exit 1 ;; esac
uid="$(id -u "$name" 2>/dev/null)" || { echo "There is no account called $name." >&2; exit 1; }
[ "$uid" -ne 0 ] || { echo "Choose a person's account, not root." >&2; exit 1; }

sed -i 's/ *--owner [^ "]*//; s/^ZPRINTD_OPTIONS="\(.*\)"/ZPRINTD_OPTIONS="\1 --owner '"$name"'"/; s/^ZPRINTD_OPTIONS=" /ZPRINTD_OPTIONS="/' "$DEFAULTS"
loginctl enable-linger "$name"
# Start the owner's agent now rather than at their next login.
systemctl --user --machine="$name@" start zprint-agent.service 2>/dev/null || true
systemctl restart zprintd.service
echo "zPrint's virtual printers now save into $name's folders."
