#!/usr/bin/env bash
#
# imath-printers.sh — adds the I-MATH institute printers to your own machine,
# so that they appear in the normal print dialog of every program.
#
# Run imath-setup.sh first: this script uses the SSH host entry "imath" that
# it creates. Nothing else is required.
#
# How it works
#   The print server print22.math.uzh.ch sits on the institute's internal
#   network -- it is not even in public DNS. From eduroam or the UZH WLAN you
#   cannot reach it; normally that means switching on the VPN every time you
#   want to print. Instead, this script routes the printers through the jump
#   host you already have SSH access to. Printing then works from any UZH
#   network without the VPN, and without a terminal. (From outside UZH the
#   jump host itself needs the VPN, so the same rule applies as for imath.)
#
#   By default the connection is opened ON DEMAND: the service "printer_uzh"
#   only listens on a local port. The moment a print job is sent, one SSH
#   connection is made. A print job is several requests, so that connection is
#   shared between them and then closes itself a minute after the last one --
#   sharing keeps the jump host from seeing dozens of logins at once. Nothing
#   is held open beyond that minute. With --always-on you get the older
#   behaviour instead: one SSH connection held open permanently.
#
# Usage
#   ./imath-printers.sh                 pick printers from a list
#   ./imath-printers.sh --uninstall     remove what this script installed
#
# Runs on macOS and Linux. Windows: use imath-printers.ps1.
#
# Idempotent: running it again adds what is missing, corrects what has
# changed and leaves everything else alone. It remembers the queues it made
# in ~/.config/imath/printers.list; a queue with the same name that points
# somewhere else is never reconfigured and never removed.
#
set -euo pipefail
export LC_ALL=C          # lpstat output is parsed; keep it in one language

PRINT_SERVER="print22.math.uzh.ch"
SSH_HOST="imath"                 # from imath-setup.sh
PORT=6631                        # local end of the tunnel
SERVICE="printer_uzh"
CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/imath"
STATE="$CONF_DIR/printers.list"  # the queues this script created
MODE_FILE="$CONF_DIR/mode"       # on-demand | always-on
SOCK_DIR="$HOME/.ssh/sockets"
CTL="$SOCK_DIR/$SERVICE"         # own control socket, separate from imath's

# Older versions of this tooling used these names.
LEGACY_LABEL="ch.uzh.math.imath-print"
LEGACY_PREFIX="IMATH-"

c_ok()   { printf '\033[32m  ok\033[0m   %s\n' "$*"; }
c_info() { printf '\033[34m  ..\033[0m   %s\n' "$*"; }
c_warn() { printf '\033[33m  !!\033[0m   %s\n' "$*"; }
c_err()  { printf '\033[31merror\033[0m %s\n' "$*" >&2; }
step()   { printf '\n\033[1m%s\033[0m\n' "$*"; }

# Half-written unit files must not survive an interrupt.
TMPFILES=""
# shellcheck disable=SC2086  # deliberate: TMPFILES is a space-separated list
cleanup() { [ -z "$TMPFILES" ] || rm -f $TMPFILES; }
trap cleanup EXIT INT TERM

ALWAYS_ON=0
OS="$(uname -s)"
case "$OS" in
    Darwin|Linux) ;;
    *) c_err "unsupported system: $OS. Windows: use imath-printers.ps1."; exit 1 ;;
esac

for prog in ssh lpadmin lpstat; do
    command -v "$prog" >/dev/null || {
        c_err "'$prog' is missing."
        [ "$prog" = lpadmin ] && c_err "Install the CUPS client (Debian/Ubuntu: apt install cups-client)."
        exit 1; }
done
SSH_BIN="$(command -v ssh)"      # not always /usr/bin/ssh (Nix, Homebrew)

# Everything this script does over SSH uses its own shared connection, so it
# neither depends on nor extends the 10-minute master that imath-setup.sh
# configures for interactive use.
ssh_q() {
    "$SSH_BIN" -o BatchMode=yes -o ConnectTimeout=15 \
        -o ControlMaster=auto -o ControlPath="$CTL" -o ControlPersist=60 "$@"
}

# --------------------------------------------------------------------------
# The tunnel
# --------------------------------------------------------------------------
tunnel_pid() {
    # Who, if anyone, listens on our port. Never fails: "nobody" is an answer.
    if command -v lsof >/dev/null 2>&1; then
        lsof -nP -iTCP:"$PORT" -sTCP:LISTEN 2>/dev/null | awk 'NR==2{print $2}'
    elif command -v ss >/dev/null 2>&1; then
        ss -lptn "sport = :$PORT" 2>/dev/null | grep -o 'pid=[0-9]*' | head -1 | cut -d= -f2 || true
    fi
    return 0
}

tunnel_alive() {
    lpstat -h "localhost:$PORT" -a >/dev/null 2>&1
}

wait_for_tunnel() {
    local i=0
    while [ "$i" -lt 12 ]; do
        tunnel_alive && return 0
        sleep 1; i=$((i+1))
    done
    return 1
}

# If a stranger holds the port, the printers would be pointed at it. Identify
# the listener first -- "something answers IPP there" is not proof it is ours.
port_is_ours_or_free() {
    local pid cmd
    pid="$(tunnel_pid)"
    if [ -z "$pid" ]; then
        tunnel_alive || return 0          # nothing listening at all: free
        c_warn "something answers on port $PORT but cannot be identified"
        c_warn "(no lsof and no ss here) — continuing."
        return 0
    fi
    cmd="$(ps -o comm= -p "$pid" 2>/dev/null || true)"
    case "$cmd" in
        *ssh*|*launchd*|*systemd*) return 0 ;;
        *) c_err "port $PORT is already taken by '${cmd:-unknown}' (pid $pid)."
           c_err "Stop that program, or change PORT at the top of this script."
           return 1 ;;
    esac
}

# systemd user units have no ssh-agent; a locked key then fails silently.
warn_if_locked_key() {
    [ "$OS" = Linux ] || return 0
    command -v ssh-keygen >/dev/null 2>&1 || return 0
    local key
    key="$("$SSH_BIN" -G "$SSH_HOST" 2>/dev/null | awk '/^identityfile /{print $2; exit}')" || return 0
    [ -n "${key:-}" ] || return 0
    case "$key" in "~"*) key="$HOME${key#\~}" ;; esac
    [ -f "$key" ] || return 0
    ssh-keygen -y -P "" -f "$key" >/dev/null 2>&1 && return 0
    c_warn "the SSH key for '$SSH_HOST' has a passphrase. A systemd user service"
    c_warn "has no agent, so print jobs may fail. Use a key without passphrase"
    c_warn "for the jump host, or run this with --always-on from a shell."
}

service_path_macos() { echo "$HOME/Library/LaunchAgents/$SERVICE.plist"; }
service_path_linux() { echo "${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$SERVICE.service"; }

# & < > in a path would produce an invalid plist, which launchd refuses.
xml_esc() { printf '%s' "$1" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'; }
# % is a specifier in systemd unit files and has to be doubled.
unit_esc() { printf '%s' "${1//%/%%}"; }

write_service_macos() {
    local f X_SSH X_CTL X_LOG X_HOST X_SRV
    f="$(service_path_macos)"
    mkdir -p "$(dirname "$f")" "$HOME/Library/Logs" "$SOCK_DIR"
    X_SSH="$(xml_esc "$SSH_BIN")"; X_CTL="$(xml_esc "$CTL")"
    X_LOG="$(xml_esc "$HOME/Library/Logs/$SERVICE.log")"
    X_HOST="$(xml_esc "$SSH_HOST")"; X_SRV="$(xml_esc "$PRINT_SERVER")"
    TMPFILES="$TMPFILES $f.new"
    if [ "$ALWAYS_ON" = 1 ]; then
        # One connection, held open.
        cat > "$f.new" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$SERVICE</string>
  <!-- Holds an SSH tunnel to the I-MATH print server open, so the institute
       printers work from any UZH network without VPN. Installed by imath-printers.sh;
       remove with: ./imath-printers.sh --uninstall -->
  <key>ProgramArguments</key>
  <array>
    <string>$X_SSH</string>
    <string>-N</string>
    <string>-o</string><string>BatchMode=yes</string>
    <string>-o</string><string>ExitOnForwardFailure=yes</string>
    <string>-o</string><string>ServerAliveInterval=30</string>
    <string>-o</string><string>ServerAliveCountMax=3</string>
    <string>-o</string><string>ConnectTimeout=15</string>
    <string>-o</string><string>ControlMaster=no</string>
    <string>-o</string><string>ControlPath=none</string>
    <string>-L</string><string>$PORT:$X_SRV:631</string>
    <string>$X_HOST</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>ThrottleInterval</key><integer>30</integer>
  <key>StandardErrorPath</key><string>$X_LOG</string>
</dict>
</plist>
EOF
    else
        # On demand: launchd holds the local port and starts one ssh per
        # connection. The connections of one print job share a single SSH
        # login, which closes 60 s after the last of them.
        cat > "$f.new" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$SERVICE</string>
  <!-- Connects to the I-MATH print server only while something is being
       printed. launchd listens on 127.0.0.1:$PORT and hands each connection
       to "ssh -W"; the SSH login is shared and closes a minute after the last
       request. Installed by imath-printers.sh; remove with:
       ./imath-printers.sh --uninstall -->
  <key>inetdCompatibility</key><dict><key>Wait</key><false/></dict>
  <key>Sockets</key>
  <dict><key>Listeners</key>
    <dict>
      <key>SockNodeName</key><string>127.0.0.1</string>
      <key>SockServiceName</key><string>$PORT</string>
    </dict>
  </dict>
  <key>ProgramArguments</key>
  <array>
    <string>$X_SSH</string>
    <string>-q</string>
    <string>-o</string><string>BatchMode=yes</string>
    <string>-o</string><string>ConnectTimeout=15</string>
    <string>-o</string><string>ControlMaster=auto</string>
    <string>-o</string><string>ControlPath=$X_CTL</string>
    <string>-o</string><string>ControlPersist=60</string>
    <string>-W</string><string>$X_SRV:631</string>
    <string>$X_HOST</string>
  </array>
  <key>StandardErrorPath</key><string>$X_LOG</string>
</dict>
</plist>
EOF
    fi
    if [ -f "$f" ] && cmp -s "$f" "$f.new"; then
        rm -f "$f.new"
        launchctl print "gui/$(id -u)/$SERVICE" >/dev/null 2>&1 || \
            launchctl bootstrap "gui/$(id -u)" "$f" 2>/dev/null || true
        c_ok "service $SERVICE is up to date"
    else
        mv "$f.new" "$f"
        launchctl bootout "gui/$(id -u)/$SERVICE" 2>/dev/null || true
        pkill -f -- "-L $PORT:$PRINT_SERVER" 2>/dev/null || true   # an older held-open tunnel
        if launchctl bootstrap "gui/$(id -u)" "$f" 2>/dev/null; then
            if [ "$ALWAYS_ON" = 1 ]; then
                c_ok "service $SERVICE installed (one connection, held open)"
            else
                c_ok "service $SERVICE installed (connects only while printing)"
            fi
        else
            c_warn "the service could not be loaded — see '$0 --status'"
        fi
    fi
}

write_service_linux() {
    local d svc sock tmpl U_SSH U_CTL changed=0 pair
    d="$(dirname "$(service_path_linux)")"
    svc="$d/$SERVICE.service"; sock="$d/$SERVICE.socket"; tmpl="$d/$SERVICE@.service"
    mkdir -p "$d" "$SOCK_DIR"
    U_SSH="$(unit_esc "$SSH_BIN")"; U_CTL="$(unit_esc "$CTL")"
    TMPFILES="$TMPFILES $svc.new $sock.new $tmpl.new"
    if [ "$ALWAYS_ON" = 1 ]; then
        # Stop the on-demand units BEFORE their files disappear, otherwise
        # systemd cannot disable what it can no longer read.
        if command -v systemctl >/dev/null 2>&1; then
            systemctl --user disable --now "$SERVICE.socket" 2>/dev/null || true
        fi
        rm -f "$sock" "$tmpl"
        cat > "$svc.new" <<EOF
[Unit]
Description=SSH tunnel to the I-MATH print server (imath-printers.sh)

[Service]
ExecStart="$U_SSH" -N -o BatchMode=yes -o ExitOnForwardFailure=yes \\
  -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -o ConnectTimeout=15 \\
  -o ControlMaster=no -o ControlPath=none \\
  -L $PORT:$PRINT_SERVER:631 $SSH_HOST
Restart=always
RestartSec=30

[Install]
WantedBy=default.target
EOF
        if [ -f "$svc" ] && cmp -s "$svc" "$svc.new"; then rm -f "$svc.new"; c_ok "service $SERVICE is up to date"
        else mv "$svc.new" "$svc"; c_ok "service $SERVICE written (one connection, held open)"; fi
        if command -v systemctl >/dev/null 2>&1; then
            systemctl --user daemon-reload 2>/dev/null || true
            pkill -f -- "-W $PRINT_SERVER:631" 2>/dev/null || true
            if systemctl --user enable --now "$SERVICE.service" 2>/dev/null; then
                c_ok "service started"
            else
                c_warn "could not start it via systemd — see --status"
            fi
        fi
    else
        # Socket activation: systemd holds the port, one ssh per connection.
        if command -v systemctl >/dev/null 2>&1; then
            systemctl --user disable --now "$SERVICE.service" 2>/dev/null || true
        fi
        rm -f "$svc"
        cat > "$sock.new" <<EOF
[Unit]
Description=Local port for the I-MATH printers (imath-printers.sh)

[Socket]
ListenStream=127.0.0.1:$PORT
Accept=yes

[Install]
WantedBy=sockets.target
EOF
        # KillMode=process: without it systemd tears down the whole cgroup when
        # the connection ends, killing the shared SSH login with it -- and the
        # next request would have to log in again.
        cat > "$tmpl.new" <<EOF
[Unit]
Description=One connection to the I-MATH print server (imath-printers.sh)

[Service]
ExecStart=-"$U_SSH" -q -o BatchMode=yes -o ConnectTimeout=15 \\
  -o ControlMaster=auto -o "ControlPath=$U_CTL" -o ControlPersist=60 \\
  -W $PRINT_SERVER:631 $SSH_HOST
StandardInput=socket
StandardOutput=socket
KillMode=process
EOF
        for pair in "$sock" "$tmpl"; do
            if [ -f "$pair" ] && cmp -s "$pair" "$pair.new"; then rm -f "$pair.new"; else mv "$pair.new" "$pair"; changed=1; fi
        done
        if [ "$changed" = 1 ]; then c_ok "service $SERVICE written (connects only while printing)"
        else c_ok "service $SERVICE is up to date"; fi
        if command -v systemctl >/dev/null 2>&1; then
            systemctl --user daemon-reload 2>/dev/null || true
            pkill -f -- "-L $PORT:$PRINT_SERVER" 2>/dev/null || true
            if systemctl --user enable --now "$SERVICE.socket" 2>/dev/null; then
                c_ok "listening on localhost:$PORT"
            else
                c_warn "could not start it via systemd — see --status"
            fi
        else
            c_warn "no systemd here. Start a tunnel yourself when you print:"
            c_warn "  ssh -f -N -L $PORT:$PRINT_SERVER:631 $SSH_HOST"
        fi
    fi
}

install_service() {
    case "$OS" in
        Darwin) write_service_macos ;;
        Linux)  write_service_linux ;;
    esac
    if [ "$ALWAYS_ON" = 1 ]; then echo always-on > "$MODE_FILE"; else echo on-demand > "$MODE_FILE"; fi
}

remove_service() {
    case "$OS" in
        Darwin)
            launchctl bootout "gui/$(id -u)/$SERVICE" 2>/dev/null || true
            rm -f "$(service_path_macos)"
            ;;
        Linux)
            if command -v systemctl >/dev/null 2>&1; then
                systemctl --user disable --now "$SERVICE.service" 2>/dev/null || true
                systemctl --user disable --now "$SERVICE.socket"  2>/dev/null || true
            fi
            rm -f "$(service_path_linux)" "$(dirname "$(service_path_linux)")/$SERVICE.socket" \
                  "$(dirname "$(service_path_linux)")/$SERVICE@.service"
            if command -v systemctl >/dev/null 2>&1; then systemctl --user daemon-reload 2>/dev/null || true; fi
            ;;
    esac
    # our own shared connection, if one is still lingering
    "$SSH_BIN" -O exit -o ControlPath="$CTL" "$SSH_HOST" >/dev/null 2>&1 || true
    pkill -f -- "-L $PORT:$PRINT_SERVER" 2>/dev/null || true
    rm -f "$MODE_FILE"
    c_ok "service $SERVICE removed"
}

# --------------------------------------------------------------------------
# Leftovers from the earlier, hand-made setup
# --------------------------------------------------------------------------
migrate_legacy() {
    if [ "$OS" = Darwin ] && [ -f "$HOME/Library/LaunchAgents/$LEGACY_LABEL.plist" ]; then
        launchctl bootout "gui/$(id -u)/$LEGACY_LABEL" 2>/dev/null || true
        rm -f "$HOME/Library/LaunchAgents/$LEGACY_LABEL.plist"
        c_ok "removed the older service $LEGACY_LABEL"
    fi
    local p
    for p in $(lpstat -v 2>/dev/null | sed -n "s/^device for ${LEGACY_PREFIX}\([^:]*\):.*/\1/p"); do
        # Only queues that point through the old local tunnel are ours. A
        # printer that merely starts with IMATH- may be somebody else's.
        case "$(queue_uri "${LEGACY_PREFIX}$p")" in
            ipp://localhost:*|ipp://127.0.0.1:*) ;;
            *) continue ;;
        esac
        if lpadmin -x "${LEGACY_PREFIX}$p" 2>/dev/null; then
            c_ok "removed the older queue ${LEGACY_PREFIX}$p (replaced by '$p')"
        fi
    done
}

# --------------------------------------------------------------------------
# Printers
# --------------------------------------------------------------------------
# Prints the queue names; on failure prints nothing, returns non-zero and puts
# the real reason on stderr.
server_queues() {
    local out err rc=0
    err="$(mktemp "${TMPDIR:-/tmp}/imath-printers.XXXXXX")" || return 1
    TMPFILES="$TMPFILES $err"
    out="$(ssh_q "$SSH_HOST" "lpstat -h $PRINT_SERVER -a" 2>"$err")" || rc=$?
    if [ "$rc" != 0 ]; then
        c_err "could not read the printer list from $PRINT_SERVER:"
        sed 's/^/       /' "$err" >&2
        rm -f "$err"; return 1
    fi
    rm -f "$err"
    printf '%s\n' "$out" | awk '{print $1}' | grep -vx UZHPrintPlus || true
}

describe() {   # a readable description for the print dialog
    case "$1" in
        *color*) echo "I-MATH $1 (colour)" ;;
        *booklet*) echo "I-MATH $1 (booklet)" ;;
        *)       echo "I-MATH $1" ;;
    esac
}

have_queue()  { lpstat -p "$1" >/dev/null 2>&1; }
queue_uri()   { lpstat -v "$1" 2>/dev/null | sed -n 's/^device for [^:]*: //p'; }
is_ours()     { grep -qxF "$1" "$STATE" 2>/dev/null; }

add_printer() {
    local q="$1" want="ipp://localhost:$PORT/printers/$1" err
    if have_queue "$q"; then
        if [ "$(queue_uri "$q")" = "$want" ]; then
            is_ours "$q" || echo "$q" >> "$STATE"
            c_ok "$q is already set up"
            return 0
        fi
        # Same name, different device: not ours. Leave it exactly as it is.
        if ! is_ours "$q"; then
            c_warn "$q already exists here and was not created by this script — left untouched."
            return 0
        fi
    fi
    # -m everywhere asks the server for the printer's real capabilities, so
    # trays, duplex and finishing options show up in the print dialog.
    if err="$(lpadmin -p "$q" -E -v "$want" -m everywhere -D "$(describe "$q")" -L "I-MATH" 2>&1)"; then
        is_ours "$q" || echo "$q" >> "$STATE"
        c_ok "$q added"
        return 0
    fi
    # A few queues on the server have no driver at all (the "-raw" ones, used
    # for pre-rendered jobs); for those there is nothing to ask for, so add
    # them without a model. Only ever do this while the tunnel is answering --
    # otherwise EVERY printer would silently become a driverless queue.
    if tunnel_alive && lpadmin -p "$q" -E -v "$want" -D "$(describe "$q")" -L "I-MATH" >/dev/null 2>&1; then
        is_ours "$q" || echo "$q" >> "$STATE"
        c_ok "$q added (no driver on the server — raw queue)"
        return 0
    fi
    c_warn "$q could not be added: ${err:-no answer from the print server}"
    return 1
}

# --------------------------------------------------------------------------
# Actions
# --------------------------------------------------------------------------
do_status() {
    step "Status"
    if tunnel_alive; then
        c_ok "tunnel is up (localhost:$PORT -> $PRINT_SERVER)"
    else
        c_warn "tunnel is NOT up — printing would queue until it is"
    fi
    case "$OS" in
        Darwin)
            if launchctl print "gui/$(id -u)/$SERVICE" >/dev/null 2>&1; then
                c_ok "service $SERVICE is loaded"
            else
                c_warn "service $SERVICE is not loaded"
            fi ;;
        Linux)
            if command -v systemctl >/dev/null 2>&1; then
                if systemctl --user is-active --quiet "$SERVICE.socket"; then
                    c_ok "service $SERVICE is listening (connects only while printing)"
                elif systemctl --user is-active --quiet "$SERVICE.service"; then
                    c_ok "service $SERVICE is active (one connection, held open)"
                else
                    c_warn "service $SERVICE is not active"
                fi
            fi ;;
    esac
    c_info "mode: $(cat "$MODE_FILE" 2>/dev/null || echo 'not installed')"
    if "$SSH_BIN" -O check -o ControlPath="$CTL" "$SSH_HOST" >/dev/null 2>&1; then
        c_info "one shared connection is open — the check above opened it; it closes by itself"
    else
        c_info "nothing connected right now"
    fi
    if [ -s "$STATE" ]; then
        printf '\n  printers installed by this script:\n'
        while read -r q || [ -n "$q" ]; do
            [ -n "$q" ] || continue
            printf '    %-16s %s\n' "$q" "$(lpstat -p "$q" 2>/dev/null | head -1 | sed 's/^printer //')"
        done < "$STATE"
    else
        printf '\n  no printers installed by this script yet\n'
    fi
    echo
    exit 0
}

do_uninstall() {
    step "Removing the I-MATH printers"
    local q gone=0 failed=""
    if [ -s "$STATE" ]; then
        while read -r q || [ -n "$q" ]; do
            [ -n "$q" ] || continue
            if ! have_queue "$q"; then gone=$((gone+1)); continue; fi   # already gone
            if lpadmin -x "$q" 2>/dev/null; then gone=$((gone+1)); else failed="$failed$q
"; fi
        done < "$STATE"
        # Keep what could not be removed, so a second run can finish the job.
        printf '%s' "$failed" > "$STATE"
        [ "$gone" = 0 ] || c_ok "$gone printer(s) removed"
        [ -z "$failed" ] || c_warn "could not remove: $(printf '%s' "$failed" | tr '\n' ' ')"
    else
        c_info "no printers were installed by this script"
    fi
    remove_service
    [ "$OS" = Darwin ] && rm -f "$HOME/Library/Logs/$SERVICE.log"
    c_info "Your SSH setup ($SSH_HOST) and everything imath-setup.sh installed stay as they are."
    exit 0
}

# --------------------------------------------------------------------------
# Arguments
# --------------------------------------------------------------------------
WANT_ALL=0; ONLY_LIST=0; SELECTED=""; MODE_FLAG=""; ACTION=""
set_action() {
    [ -z "$ACTION" ] || { c_err "use only one of --status / --uninstall."; exit 1; }
    ACTION="$1"
}
while [ $# -gt 0 ]; do
    case "$1" in
        --all)       WANT_ALL=1; shift ;;
        --always-on) MODE_FLAG=always-on; shift ;;
        --on-demand) MODE_FLAG=on-demand; shift ;;
        --list)      ONLY_LIST=1; shift ;;
        --status)    set_action status; shift ;;
        --uninstall) set_action uninstall; shift ;;
        -h|--help)   awk 'NR>1 && /^#/ {sub(/^# ?/,""); print; next} NR>1 {exit}' "$0"; exit 0 ;;
        -*)          c_err "unknown option: $1"; exit 1 ;;
        *)           SELECTED="$SELECTED $1"; shift ;;
    esac
done
set -f      # printer names are names, not shell patterns

if [ "$WANT_ALL" = 1 ] && [ -n "${SELECTED// /}" ]; then
    c_err "--all and a list of printer names cannot be combined."; exit 1
fi
if [ -n "$ACTION" ] && { [ "$WANT_ALL" = 1 ] || [ "$ONLY_LIST" = 1 ] || [ -n "${SELECTED// /}" ]; }; then
    c_err "--$ACTION takes no other arguments."; exit 1
fi
if [ "$ONLY_LIST" = 1 ] && { [ "$WANT_ALL" = 1 ] || [ -n "${SELECTED// /}" ]; }; then
    c_err "--list takes no other arguments."; exit 1
fi

# Remember which mode was chosen, so a later "add one more printer" run does
# not silently switch an --always-on installation back to on-demand.
if [ -n "$MODE_FLAG" ]; then
    [ "$MODE_FLAG" = always-on ] && ALWAYS_ON=1 || ALWAYS_ON=0
elif [ "$(cat "$MODE_FILE" 2>/dev/null || true)" = always-on ]; then
    ALWAYS_ON=1
fi

[ "$ACTION" = status ] && do_status
[ "$ACTION" = uninstall ] && do_uninstall

# --------------------------------------------------------------------------
step "I-MATH printers"

# 1. the jump host must work (imath-setup.sh)
if ! ssh_q "$SSH_HOST" true 2>/dev/null; then
    c_err "cannot reach the jump host over the SSH host entry '$SSH_HOST'."
    c_err "Run imath-setup.sh first — this script builds on it."
    exit 1
fi
c_ok "jump host reachable"

# 2. what does the institute have? (read over the jump host, no tunnel yet)
QUEUES="$(server_queues)" || exit 1
if [ -z "$QUEUES" ]; then
    c_err "the print server did not list any printers."
    exit 1
fi
COUNT="$(printf '%s\n' "$QUEUES" | wc -l | tr -d ' ')"

# 3. --list changes nothing, so it must return before anything is touched --
#    including before the config directory is created.
if [ "$ONLY_LIST" = 1 ]; then
    step "Printers at the institute ($COUNT)"
    printf '%s\n' "$QUEUES" | awk '{printf "  %-16s", $1; if (NR % 4 == 0) printf "\n"} END {printf "\n"}'
    echo
    exit 0
fi

mkdir -p "$CONF_DIR"
touch "$STATE"

# 4. an older, hand-made setup may still hold the port with its own service
migrate_legacy

# 5. which ones does this person want?
CHOICE=""
if [ -n "${SELECTED// /}" ]; then
    for q in $SELECTED; do
        if printf '%s\n' "$QUEUES" | grep -qxF "$q"; then CHOICE="$CHOICE $q"
        else c_warn "'$q' is not a printer of the institute — ignored"; fi
    done
    [ -n "${CHOICE// /}" ] || { c_err "nothing to do."; exit 1; }
elif [ "$WANT_ALL" = 1 ]; then
    CHOICE="$QUEUES"
elif [ -t 0 ]; then
    step "Printers at the institute ($COUNT)"
    NUMBERED="$(printf '%s\n' "$QUEUES" | nl -ba -w3 -s'  ')"
    printf '%s\n' "$NUMBERED" | awk '{printf "  %-24s", $0; if (NR % 3 == 0) printf "\n"} END {printf "\n"}'
    echo
    echo "  Which ones do you want?"
    echo "    a          all of them"
    echo "    1 5 9      by number, separated by spaces"
    echo "    h52 j      or simply by name"
    echo "    <Enter>    cancel"
    printf '  > '
    read -r ANSWER || ANSWER=""          # Ctrl-D is a cancel, not a crash
    case "${ANSWER:-}" in
        "")   c_info "nothing selected — nothing changed."; exit 0 ;;
        a|A|all) CHOICE="$QUEUES" ;;
        *)    for tok in $ANSWER; do
                  case "$tok" in
                      # a real number, 1..999 -- "0" and "3x" are not
                      [1-9]|[1-9][0-9]|[1-9][0-9][0-9])
                              if [ "$tok" -le "$COUNT" ]; then
                                  q="$(printf '%s\n' "$QUEUES" | sed -n "${tok}p")"
                                  CHOICE="$CHOICE $q"
                              else
                                  c_warn "no printer number $tok"
                              fi ;;
                      *)      if printf '%s\n' "$QUEUES" | grep -qxF "$tok"; then CHOICE="$CHOICE $tok"
                              else c_warn "'$tok' is neither a number nor a printer of the institute — ignored"; fi ;;
                  esac
              done ;;
    esac
    [ -n "${CHOICE// /}" ] || { c_info "nothing selected — nothing changed."; exit 0; }
else
    c_err "no printer given and no terminal to ask in."
    c_err "Use --all, or name them: $0 h52 jcolor"
    exit 1
fi

# 6. the service first — it is what gives the printers their local port
step "Background service"
port_is_ours_or_free || exit 1
warn_if_locked_key
install_service
if ! wait_for_tunnel; then
    c_err "the local print port is not answering. No printer was touched."
    c_err "Check it with:  $0 --status"
    exit 1
fi
c_ok "local print port answers"

# 7. the printers themselves
step "Setting up the printers"
for q in $CHOICE; do add_printer "$q" || true; done

# 8. does it actually work?
step "Check"
if tunnel_alive; then
    c_ok "tunnel answers — printing works from any UZH network, no VPN"
else
    c_warn "the tunnel is not answering any more. Check with: $0 --status"
fi
printf '\n'
for q in $CHOICE; do
    printf '    %-16s %s\n' "$q" "$(lpstat -p "$q" 2>/dev/null | head -1 | sed 's/^printer [^ ]* //')"
done

cat <<EOF

Done. The printers are in the normal print dialog of every program now
(macOS: System Settings > Printers & Scanners, Linux: your desktop's
printer settings). On eduroam, the institute WLAN or a cable: just print,
no VPN and no terminal. From outside UZH, switch on the VPN first — the
jump host is not reachable without it.

  $0 --status       is everything running?
  $0 --list         which printers does the institute have?
  $0 h52 jcolor     add more later
  $0 --uninstall    remove everything this script installed

If a job waits instead of printing, you are simply offline: it goes out by
itself as soon as the machine has internet again.
EOF
