Set up Pop!_OS for a Federated Core, like CoreDesktop's configure
A port of CoreDesktop's configure to Pop!_OS 24.04 with COSMIC, in the shape of connector-macos: its own install.sh, update and configure, installed in ~/.local/share/federated-connector/connector. Every configure item is ported: the Core (email, calendars and contacts through GNOME Online Accounts and Evolution, as COSMIC has no accounts of its own; Superpanel; files over davfs2; Element; Tally; the email watcher), Tailscale, backups, AI agents in the sandbox and their sign-ins, languages with mise, AI servers, printers, network storage and the agent sandbox. Folders go in the COSMIC Files sidebar. Each item installs what it needs from apt, Flathub or the tool's own apt repository when you set it up. smoketest/run checks it in Ubuntu 24.04 containers with Docker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Executable
+104
@@ -0,0 +1,104 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Purpose : Back up your home folder with restic to your Nextcloud files, in
|
||||
# .backup-<hostname>. Run daily by federated-connector-backup.timer;
|
||||
# `configure backup` sets it up.
|
||||
#
|
||||
# Keeps 7 daily, 4 weekly and 6 monthly backups. To leave out more, list
|
||||
# paths or patterns in ~/.config/federated-connector/backup-exclude, one per line.
|
||||
|
||||
# Wrapped in { ...; exit; } so bash reads the whole script up front; update
|
||||
# replaces this file while a backup may be running.
|
||||
{
|
||||
|
||||
CONNECTOR="$(cd "$(dirname "$(realpath "$0")")/.." && pwd)"
|
||||
USER_EXCLUDE="$HOME/.config/federated-connector/backup-exclude"
|
||||
LOG_HINT="See: journalctl --user -u federated-connector-backup"
|
||||
|
||||
# Tell the desktop when a backup fails, as no one watches the timer
|
||||
fail() {
|
||||
echo "$1" >&2
|
||||
notify-send --app-name="Federated Connector" --icon=dialog-error "Backup failed" "$1" 2> /dev/null
|
||||
exit 1
|
||||
}
|
||||
|
||||
source "$CONNECTOR/system/backup-env.sh" || exit 1
|
||||
[ -n "$RESTIC_REPOSITORY" ] || fail "Backups aren't set up. Run: configure backup"
|
||||
[ -n "$RESTIC_PASSWORD_COMMAND" ] || fail "The backup's passphrase isn't in your keyring. Run: configure backup"
|
||||
|
||||
# Run at login, perhaps before the network is up; give it a few minutes
|
||||
for _ in {1..10}; do
|
||||
curl -sf --max-time 10 -o /dev/null "${BACKUP_WEBDAV%%/remote.php/*}/status.php" && break
|
||||
sleep 30
|
||||
done
|
||||
|
||||
# Rebuilt by restic, or by reinstalling, so not worth the space
|
||||
excludes=(
|
||||
"$HOME/.cache"
|
||||
"$HOME/.davfs2/cache"
|
||||
"$HOME/.local/share/Trash"
|
||||
"$HOME/.local/share/containers"
|
||||
"$HOME/.local/share/flatpak"
|
||||
"$HOME/.local/share/federated-connector"
|
||||
"$HOME/.var/app/*/cache"
|
||||
"$HOME/.nv"
|
||||
# Package caches and tool installs
|
||||
"$HOME/.npm"
|
||||
"$HOME/.bun/install/cache"
|
||||
"$HOME/.cargo/registry"
|
||||
"$HOME/.cargo/git"
|
||||
"$HOME/go/pkg"
|
||||
"$HOME/.local/share/mise/installs"
|
||||
"$HOME/.local/share/mise/downloads"
|
||||
"$HOME/.local/share/uv"
|
||||
"$HOME/.local/share/pipx"
|
||||
"$HOME/.local/share/claude"
|
||||
"$HOME/.local/share/nvim/lazy"
|
||||
"$HOME/.local/share/nvim/mason"
|
||||
# The agents' own installs and downloads; their settings, memories and
|
||||
# sessions are kept
|
||||
"$HOME/.hermes/hermes-agent"
|
||||
"$HOME/.hermes/tools"
|
||||
"$HOME/.hermes/installs"
|
||||
"$HOME/.hermes/bin"
|
||||
"$HOME/.hermes/cache"
|
||||
"$HOME/.hermes/audio_cache"
|
||||
"$HOME/.hermes/image_cache"
|
||||
# LM Studio's models and engines can be downloaded again
|
||||
"$HOME/.lmstudio/models"
|
||||
"$HOME/.lmstudio/extensions"
|
||||
"$HOME/.lmstudio/bin"
|
||||
# Electron and Chromium apps (Element, browsers, editors) keep caches here
|
||||
"$HOME/.config/*/Cache"
|
||||
"$HOME/.config/**/Code Cache"
|
||||
"$HOME/.config/**/GPUCache"
|
||||
"$HOME/.config/**/GrShaderCache"
|
||||
"$HOME/.config/**/GPUPersistentCache"
|
||||
"$HOME/.config/**/DawnGraphiteCache"
|
||||
"$HOME/.config/**/DawnWebGPUCache"
|
||||
"$HOME/.config/**/Service Worker/CacheStorage"
|
||||
# Element's search index for encrypted messages, which it rebuilds
|
||||
"$HOME/.config/Element/EventStore"
|
||||
# WinBoat's Windows VM: its disk is large, and changes whenever Windows runs
|
||||
"$HOME/winboat"
|
||||
)
|
||||
exclude_args=(--exclude-caches)
|
||||
for path in "${excludes[@]}"; do
|
||||
exclude_args+=(--exclude "$path")
|
||||
done
|
||||
[ -f "$USER_EXCLUDE" ] && exclude_args+=(--exclude-file "$USER_EXCLUDE")
|
||||
|
||||
echo "Backing up $HOME to $BACKUP_DIR in your Nextcloud files..."
|
||||
# --one-file-system leaves out other mounts and btrfs subvolumes inside home
|
||||
restic backup --one-file-system --host "$HOSTNAME" "${exclude_args[@]}" "$HOME"
|
||||
status=$?
|
||||
# 3 means some files couldn't be read; the rest were backed up
|
||||
(( status == 0 || status == 3 )) || fail "restic couldn't back up $HOME (exit $status). $LOG_HINT"
|
||||
|
||||
echo "Removing old backups..."
|
||||
restic forget --host "$HOSTNAME" --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune \
|
||||
|| fail "restic couldn't remove old backups. $LOG_HINT"
|
||||
|
||||
echo "Backup finished."
|
||||
exit 0
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Purpose : Point restic at your backup in your Nextcloud files. Sourced by
|
||||
# system/backup and configure.d/20-backup.sh, and by you to look at
|
||||
# or restore from a backup:
|
||||
#
|
||||
# source ~/.local/share/federated-connector/connector/system/backup-env.sh
|
||||
# restic snapshots
|
||||
#
|
||||
# To use another computer's backup, name its folder:
|
||||
#
|
||||
# source ~/.local/share/federated-connector/connector/system/backup-env.sh .backup-<name>
|
||||
#
|
||||
# restic reaches Nextcloud over WebDAV through rclone, not the davfs2 mount,
|
||||
# which can't safely replace files. The Nextcloud app password and the
|
||||
# backup's passphrase are kept in your keyring.
|
||||
|
||||
BACKUP_CONF="$HOME/.config/federated-connector/backup.conf"
|
||||
|
||||
# A secret from the keyring: nextcloud (app password) or passphrase
|
||||
backup_secret() {
|
||||
secret-tool lookup federated-connector backup item "$1" url "$2"
|
||||
}
|
||||
|
||||
if [ -f "$BACKUP_CONF" ]; then
|
||||
source "$BACKUP_CONF"
|
||||
BACKUP_DIR="${1:-$BACKUP_DIR}"
|
||||
|
||||
export RCLONE_WEBDAV_URL="$BACKUP_WEBDAV"
|
||||
export RCLONE_WEBDAV_VENDOR=nextcloud
|
||||
export RCLONE_WEBDAV_USER="$BACKUP_USER"
|
||||
RCLONE_WEBDAV_PASS="$(backup_secret nextcloud "$BACKUP_WEBDAV" | rclone obscure -)"
|
||||
export RCLONE_WEBDAV_PASS
|
||||
export RESTIC_REPOSITORY="rclone::webdav:$BACKUP_DIR"
|
||||
|
||||
# Without a passphrase in the keyring, e.g. for another computer's backup,
|
||||
# restic asks for it
|
||||
unset RESTIC_PASSWORD_COMMAND
|
||||
if [ -n "$(backup_secret passphrase "$BACKUP_WEBDAV/$BACKUP_DIR")" ]; then
|
||||
export RESTIC_PASSWORD_COMMAND="secret-tool lookup federated-connector backup item passphrase url $BACKUP_WEBDAV/$BACKUP_DIR"
|
||||
fi
|
||||
else
|
||||
echo "Backups aren't set up. Run: configure backup" >&2
|
||||
fi
|
||||
Executable
+227
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pause a Core's email in Online Accounts when its password stops working.
|
||||
|
||||
When your Core password changes (e.g. in Superpanel), email in Online Accounts
|
||||
still has the old one. Online Accounts signs in with it each time the network
|
||||
changes, and Evolution each time it fetches mail, and after a few wrong
|
||||
passwords the mail server's fail2ban blocks this computer.
|
||||
|
||||
Online Accounts doesn't reliably say when a mail server refuses a password:
|
||||
3.50, which Pop!_OS 24.04 has, marks an account as needing attention for any
|
||||
failure, including a server it can't reach, and 3.58 reports a refused mail
|
||||
password as a general failure. It does say when Nextcloud refuses one, and Nextcloud
|
||||
turns off its app passwords when your Core password changes. So when the
|
||||
Core's Nextcloud in Online Accounts needs attention, this signs in to Nextcloud,
|
||||
once, with the password email has (your Core password). If Nextcloud says it's
|
||||
wrong, the mail server will too, so this pauses email
|
||||
(configure.d/lib/goa-account pause): nothing signs in with the old password
|
||||
again. It shows a notification; clicking it runs configure core, where "Your
|
||||
Core password changed" saves the new password and ends the pause. It never
|
||||
signs in to the mail server itself.
|
||||
|
||||
Run by federated-connector-email-watch.service, which configure core installs.
|
||||
|
||||
email-watch --check-password <email> checks the password email has with
|
||||
Nextcloud, as above, for configure core's tests: it exits 0 if it works, 2 if
|
||||
Nextcloud says it's wrong, 1 if it couldn't tell.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import glob
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib # noqa: E402
|
||||
|
||||
CONNECTOR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
RUN_IN_TERMINAL = os.path.join(CONNECTOR, "system/run-in-terminal")
|
||||
CORES = os.path.expanduser("~/.config/federated-connector/cores/*.conf")
|
||||
|
||||
|
||||
def load_goa_account():
|
||||
# No __pycache__ in the installed copy, which update replaces
|
||||
sys.dont_write_bytecode = True
|
||||
path = os.path.join(CONNECTOR, "configure.d/lib/goa-account")
|
||||
loader = importlib.machinery.SourceFileLoader("goa_account", path)
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader("goa_account", loader))
|
||||
loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
goa = load_goa_account()
|
||||
|
||||
|
||||
# Each Core's email and domain, from configure core's cores/<domain>.conf
|
||||
def cores():
|
||||
found = {}
|
||||
for conf in glob.glob(CORES):
|
||||
result = subprocess.run(
|
||||
["bash", "-c", 'source "$1" && printf "%s\\n%s\\n" "$CORE_EMAIL" "$CORE_DOMAIN"', "-", conf],
|
||||
capture_output=True, text=True)
|
||||
lines = result.stdout.split("\n")
|
||||
if result.returncode == 0 and len(lines) >= 2 and lines[0] and lines[1]:
|
||||
found[lines[0]] = lines[1]
|
||||
return found
|
||||
|
||||
|
||||
def nextcloud_url(domain):
|
||||
return f"https://nextcloud.{domain}"
|
||||
|
||||
|
||||
# Sign in to the Core's Nextcloud with the password email has, the way
|
||||
# configure core checks a password (configure.d/lib/nextcloud.sh). True if it
|
||||
# works, False if Nextcloud says it's wrong, None if it couldn't tell.
|
||||
def nextcloud_takes(email, domain, password):
|
||||
user = email.rsplit("@", 1)[0]
|
||||
auth = base64.b64encode(f"{user}:{password}".encode()).decode()
|
||||
request = urllib.request.Request(
|
||||
f"{nextcloud_url(domain)}/ocs/v2.php/cloud/user?format=json",
|
||||
headers={"Authorization": f"Basic {auth}", "OCS-APIRequest": "true"})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15):
|
||||
return True
|
||||
except urllib.error.HTTPError as error:
|
||||
return False if error.code == 401 else None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def email_password(bus, email):
|
||||
for _, account in goa.find_accounts(bus, "imap_smtp", email):
|
||||
return goa.lookup_credentials("imap_smtp", account["Id"]).get("imap-password")
|
||||
return None
|
||||
|
||||
|
||||
def check_password(bus, email):
|
||||
domain = cores().get(email)
|
||||
if domain is None:
|
||||
return None
|
||||
password = email_password(bus, email)
|
||||
if not password:
|
||||
return None
|
||||
return nextcloud_takes(email, domain, password)
|
||||
|
||||
|
||||
# Waits for a click in its own thread, so the watching goes on meanwhile
|
||||
def notify(email, domain, paused_now):
|
||||
def run():
|
||||
if paused_now:
|
||||
body = (f"Your Core password seems to have changed: {email} has the old one. "
|
||||
"So the mail server doesn't block this computer for trying it, it's "
|
||||
"paused. Click to enter your new password.")
|
||||
else:
|
||||
body = (f"{email} is paused because it has an old password. "
|
||||
"Click to enter your new Core password.")
|
||||
result = subprocess.run(
|
||||
["notify-send", "--wait", "--app-name=Federated Connector", "--icon=mail-unread",
|
||||
"--action=default=Fix", "--action=fix=Enter new password",
|
||||
f"Email for {domain} is paused", body],
|
||||
capture_output=True, text=True)
|
||||
if result.stdout.strip() in ("default", "fix"):
|
||||
subprocess.run([RUN_IN_TERMINAL, "configure core"])
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
|
||||
|
||||
# Emails already dealt with since they started failing, so each is checked and
|
||||
# notified about once until it works again
|
||||
handled = set()
|
||||
|
||||
|
||||
def check(bus):
|
||||
try:
|
||||
accounts = {(account.get("ProviderType"), account.get("PresentationIdentity")): account
|
||||
for _, account in goa.accounts(bus)}
|
||||
except GLib.Error:
|
||||
return
|
||||
for email, domain in cores().items():
|
||||
mail = accounts.get(("imap_smtp", email))
|
||||
if mail is None:
|
||||
continue
|
||||
nextcloud = accounts.get(("owncloud", f"{email.rsplit('@', 1)[0]}@nextcloud.{domain}"))
|
||||
mail_failing = bool(mail.get("AttentionNeeded"))
|
||||
nextcloud_failing = bool(nextcloud and nextcloud.get("AttentionNeeded"))
|
||||
if not mail_failing and not nextcloud_failing:
|
||||
handled.discard(email)
|
||||
continue
|
||||
if email in handled:
|
||||
continue
|
||||
|
||||
try:
|
||||
if goa.paused(bus, "imap_smtp", email):
|
||||
handled.add(email)
|
||||
notify(email, domain, False)
|
||||
continue
|
||||
# Nextcloud may only have had an app password revoked, and email may
|
||||
# still be marked from a pause whose new password hasn't been
|
||||
# checked yet, so check the password email has before pausing it
|
||||
password = email_password(bus, email)
|
||||
if not password:
|
||||
continue # e.g. the keyring is locked; try again later
|
||||
works = nextcloud_takes(email, domain, password)
|
||||
if works is None:
|
||||
continue # try again when the network changes
|
||||
if works:
|
||||
handled.add(email)
|
||||
continue
|
||||
goa.pause(bus, "imap_smtp", email)
|
||||
except (GLib.Error, LookupError):
|
||||
continue
|
||||
handled.add(email)
|
||||
notify(email, domain, True)
|
||||
|
||||
|
||||
def watch():
|
||||
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
pending = []
|
||||
|
||||
# Signals come in bursts; check once they've settled
|
||||
def queue_check(*_):
|
||||
if not pending:
|
||||
pending.append(GLib.timeout_add_seconds(2, run_check))
|
||||
|
||||
def run_check():
|
||||
pending.clear()
|
||||
check(bus)
|
||||
return GLib.SOURCE_REMOVE
|
||||
|
||||
account = "org.gnome.OnlineAccounts.Account"
|
||||
bus.signal_subscribe(goa.BUS_NAME, "org.freedesktop.DBus.Properties", "PropertiesChanged",
|
||||
None, account, Gio.DBusSignalFlags.NONE, queue_check)
|
||||
bus.signal_subscribe(goa.BUS_NAME, "org.freedesktop.DBus.ObjectManager", "InterfacesAdded",
|
||||
None, None, Gio.DBusSignalFlags.NONE, queue_check)
|
||||
# Online Accounts checks every account when it starts, e.g. at login, and
|
||||
# when the network changes
|
||||
bus.signal_subscribe("org.freedesktop.DBus", "org.freedesktop.DBus", "NameOwnerChanged",
|
||||
"/org/freedesktop/DBus", goa.BUS_NAME, Gio.DBusSignalFlags.NONE, queue_check)
|
||||
Gio.NetworkMonitor.get_default().connect("network-changed", queue_check)
|
||||
queue_check()
|
||||
GLib.MainLoop().run()
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--check-password":
|
||||
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
try:
|
||||
works = check_password(bus, sys.argv[2])
|
||||
except (GLib.Error, LookupError):
|
||||
works = None
|
||||
return {True: 0, False: 2, None: 1}[works]
|
||||
if len(sys.argv) == 1:
|
||||
watch()
|
||||
return 0
|
||||
print(__doc__.strip().split("\n\n")[-1], file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Purpose : Run a command in a new terminal window, for notifications that
|
||||
# start something when clicked (system/email-watch).
|
||||
#
|
||||
# run-in-terminal <command>, e.g. run-in-terminal "configure core"
|
||||
#
|
||||
# bash -i reads ~/.bashrc, as if you had typed the command yourself, and the
|
||||
# window stays open to show how it went.
|
||||
|
||||
run=(bash -ic "$1; echo; read -rp \"Press Enter to close this window.\"")
|
||||
if command -v cosmic-term &> /dev/null; then
|
||||
terminal=(cosmic-term -e)
|
||||
elif command -v xdg-terminal-exec &> /dev/null; then
|
||||
terminal=(xdg-terminal-exec)
|
||||
elif command -v gnome-terminal &> /dev/null; then
|
||||
terminal=(gnome-terminal --)
|
||||
elif command -v x-terminal-emulator &> /dev/null; then
|
||||
terminal=(x-terminal-emulator -e)
|
||||
else
|
||||
notify-send --app-name="Federated Connector" "No terminal found" "Open a terminal and run $1."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Run the terminal as its own unit: when the service that called this exits,
|
||||
# systemd stops everything still running in it, which would close the terminal
|
||||
exec systemd-run --user --quiet --collect -- "${terminal[@]}" "${run[@]}"
|
||||
Executable
+406
@@ -0,0 +1,406 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Purpose : Find the printers on the network and add them as permanent CUPS
|
||||
# queues, so they show up in every print dialog. `configure printers`
|
||||
# runs this; run it yourself for the options below (--help).
|
||||
#
|
||||
# Printers announce themselves over mDNS, and CUPS prints to them through
|
||||
# temporary queues that only exist while in use. Chromium browsers list
|
||||
# those, but the GTK print dialog ("Print using system dialog...") often lists
|
||||
# only permanent queues, so a printer can show up in the browser but not
|
||||
# there. `lpstat -v` then says "No
|
||||
# destinations added" while `lpstat -e` lists the printers. A permanent queue
|
||||
# made with `lpadmin -m everywhere` (driverless IPP Everywhere) fixes that.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONNECTOR="$(cd "$(dirname "$(realpath "${BASH_SOURCE[0]}")")/.." && pwd)"
|
||||
source "$CONNECTOR/configure.d/lib/mdns.sh"
|
||||
|
||||
TEST_PAGE=/usr/share/cups/data/default-testpage.pdf
|
||||
|
||||
usage() {
|
||||
cat << 'EOF'
|
||||
Usage: setup-printers.sh [options]
|
||||
|
||||
Finds the printers on your network and adds the ones you choose as permanent
|
||||
CUPS queues, so they show up in every print dialog.
|
||||
|
||||
--all Add every printer found, without asking (a printer another
|
||||
computer shares is left out when it can be reached directly)
|
||||
--default NAME Make queue NAME the default printer afterwards
|
||||
--dry-run Show the commands that would change the system; run none
|
||||
--no-deps Don't install packages or turn on services
|
||||
--test-page Print a test page on each queue added
|
||||
-h, --help Show this help
|
||||
|
||||
If a printer is still missing from a print dialog:
|
||||
- Quit the app completely (browsers especially) and open it again; print
|
||||
dialogs read the list of printers when they start.
|
||||
- GTK needs its CUPS print backend:
|
||||
ls /usr/lib/*/gtk-3.0/*/printbackends /usr/lib/*/gtk-4.0/*/printbackends
|
||||
If only the "file" backend is there: sudo apt install --reinstall libgtk-3-0t64
|
||||
- Flatpak apps print through the portal (xdg-desktop-portal); the app may
|
||||
also need: flatpak override --user --socket=cups <app id>
|
||||
- $CUPS_SERVER or ~/.cups/client.conf can point apps at another CUPS server
|
||||
than this computer's.
|
||||
- To see what the dialog does: GTK_DEBUG=printing <app>, while watching
|
||||
journalctl -fu cups
|
||||
- cups-browsed can add queues for the printers it finds by itself, instead
|
||||
of this script; this one adds only the queues you choose.
|
||||
EOF
|
||||
}
|
||||
|
||||
DRY_RUN=false ALL=false NO_DEPS=false PRINT_TEST=false DEFAULT=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--all) ALL=true ;;
|
||||
--default)
|
||||
[ $# -ge 2 ] || { echo "--default needs a queue name." >&2; exit 2; }
|
||||
DEFAULT="$2"
|
||||
shift ;;
|
||||
--dry-run) DRY_RUN=true ;;
|
||||
--no-deps) NO_DEPS=true ;;
|
||||
--test-page) PRINT_TEST=true ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) echo "Unknown option: $1 (see --help)" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# Run a command that changes the system, or with --dry-run only show it
|
||||
run() {
|
||||
if $DRY_RUN; then
|
||||
printf ' would run:'
|
||||
printf ' %q' "$@"
|
||||
echo
|
||||
else
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
|
||||
# --- Step 1: packages and services ------------------------------------------
|
||||
|
||||
setup_dependencies() {
|
||||
local pkg service line new backup missing=() stopped=()
|
||||
|
||||
for pkg in cups avahi-daemon avahi-utils libnss-mdns; do
|
||||
[ "$(dpkg-query -W -f '${db:Status-Status}' "$pkg" 2> /dev/null)" = installed ] || missing+=("$pkg")
|
||||
done
|
||||
if [ ${#missing[@]} -gt 0 ]; then
|
||||
echo "Installing ${missing[*]}..."
|
||||
run sudo apt-get install -y "${missing[@]}"
|
||||
fi
|
||||
|
||||
for service in cups.service avahi-daemon.service; do
|
||||
if ! systemctl is-enabled -q "$service" 2> /dev/null || ! systemctl is-active -q "$service"; then
|
||||
stopped+=("$service")
|
||||
fi
|
||||
done
|
||||
if [ ${#stopped[@]} -gt 0 ]; then
|
||||
echo "Turning on ${stopped[*]}..."
|
||||
run sudo systemctl enable --now "${stopped[@]}"
|
||||
fi
|
||||
|
||||
# Without mdns_minimal (Ubuntu's libnss-mdns adds mdns4_minimal, IPv4
|
||||
# only), the .local names in printers' addresses don't resolve
|
||||
line="$(grep -m1 '^hosts:' /etc/nsswitch.conf || true)"
|
||||
if [[ "$line" != *"mdns_minimal [NOTFOUND=return]"* && "$line" != *"mdns4_minimal [NOTFOUND=return]"* ]]; then
|
||||
if [[ "$line" == *" resolve"* ]]; then
|
||||
new="${line/ resolve/ mdns_minimal [NOTFOUND=return] resolve}"
|
||||
elif [[ "$line" == *" dns"* ]]; then
|
||||
new="${line/ dns/ mdns_minimal [NOTFOUND=return] dns}"
|
||||
else
|
||||
new="${line:-hosts:} mdns_minimal [NOTFOUND=return]"
|
||||
fi
|
||||
backup="/etc/nsswitch.conf.bak.$(date +%Y%m%d%H%M%S)"
|
||||
echo "Letting .local names resolve, in /etc/nsswitch.conf (a copy is kept in $backup):"
|
||||
echo " before: $line"
|
||||
echo " after: $new"
|
||||
run sudo cp -p /etc/nsswitch.conf "$backup"
|
||||
if [ -n "$line" ]; then
|
||||
run sudo sed -i "s|^hosts:.*|$new|" /etc/nsswitch.conf
|
||||
else
|
||||
echo "$new" | run sudo tee -a /etc/nsswitch.conf > /dev/null
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
$NO_DEPS || setup_dependencies
|
||||
|
||||
if ! LC_ALL=C lpstat -r 2> /dev/null | grep -q "scheduler is running"; then
|
||||
echo "CUPS isn't running, so printers can't be found or added." >&2
|
||||
echo "Start it with: sudo systemctl enable --now cups.service" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- Step 2: find printers ----------------------------------------------------
|
||||
|
||||
# %20 -> space, %40 -> @ and any other percent escape
|
||||
url_decode() {
|
||||
local s="${1//\\/\\\\}"
|
||||
printf '%b' "${s//%/\\x}"
|
||||
}
|
||||
|
||||
# Printers can take a few seconds to answer
|
||||
echo "Looking for printers..."
|
||||
found=""
|
||||
for attempt in 1 2 3; do
|
||||
found="$(LC_ALL=C lpinfo --include-schemes dnssd -v 2> /dev/null | grep '^network dnssd://' || true)"
|
||||
[ -n "$found" ] && break
|
||||
[ "$attempt" -lt 3 ] && sleep 3
|
||||
done
|
||||
if [ -z "$found" ]; then
|
||||
echo "No printers found on the network. Is the printer on, and on the same network?"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# What Avahi knows about each printer, by name: its host, address, port and
|
||||
# path, for spotting queues that already reach it and for the ipp:// fallback
|
||||
declare -A AVAHI_HOST=() AVAHI_ADDR=() AVAHI_PORT=() AVAHI_RP=()
|
||||
while IFS='|' read -r name _ host address port txt; do
|
||||
[ -n "$name" ] || continue
|
||||
AVAHI_HOST["$name"]="$host" AVAHI_ADDR["$name"]="$address" AVAHI_PORT["$name"]="$port"
|
||||
if [[ "$txt" =~ \"rp=([^\"]*)\" ]]; then
|
||||
AVAHI_RP["$name"]="${BASH_REMATCH[1]}"
|
||||
fi
|
||||
done < <(mdns_services _ipp._tcp || true)
|
||||
|
||||
# One entry per printer found: P_NAME is its name as shown, P_BASE the name
|
||||
# without the "@ host" of a shared printer, P_SHARER that host
|
||||
P_NAME=() P_BASE=() P_URI=() P_SHARER=()
|
||||
dnssd='^dnssd://([^/]+)\._ipps?\._tcp\.[^/]*(/[^?]*)'
|
||||
while read -r _ uri; do
|
||||
[[ "$uri" =~ $dnssd ]] || continue
|
||||
name="$(url_decode "${BASH_REMATCH[1]}")"
|
||||
path="${BASH_REMATCH[2]}"
|
||||
sharer=""
|
||||
# Another computer's CUPS shares it, as "<printer> @ <computer>"
|
||||
if [[ "$path" == /cups* && "$name" == *" @ "* ]]; then
|
||||
sharer="${name##* @ }"
|
||||
fi
|
||||
P_NAME+=("$name") P_BASE+=("${name% @ *}") P_URI+=("$uri") P_SHARER+=("$sharer")
|
||||
done <<< "$found"
|
||||
[ "${#P_NAME[@]}" -gt 0 ] || { echo "No printers found on the network."; exit 0; }
|
||||
|
||||
# A shared printer that can also be reached directly: the direct one is used,
|
||||
# so printing doesn't depend on the other computer being on
|
||||
P_DUP=()
|
||||
for i in "${!P_NAME[@]}"; do
|
||||
P_DUP[i]=""
|
||||
[ -n "${P_SHARER[i]}" ] || continue
|
||||
for j in "${!P_NAME[@]}"; do
|
||||
if [ -z "${P_SHARER[j]}" ] && [ "${P_NAME[j]}" = "${P_BASE[i]}" ]; then
|
||||
P_DUP[i]="$j"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
# --- Step 3: queue names ------------------------------------------------------
|
||||
|
||||
# The queues there are now: name -> device URI
|
||||
declare -A QUEUE_URI=()
|
||||
while read -r _ _ queue uri; do
|
||||
QUEUE_URI["${queue%:}"]="$uri"
|
||||
done < <(LC_ALL=C lpstat -v 2> /dev/null | grep '^device for ' || true)
|
||||
|
||||
lower() {
|
||||
tr '[:upper:]' '[:lower:]' <<< "${1%.}"
|
||||
}
|
||||
|
||||
# The queue that already prints to printer $1, if any: one with the same URI,
|
||||
# or one made some other way (e.g. cups-browsed or system-config-printer) that reaches the same host
|
||||
# and path, like ipp://NPI3BE90A.local:631/ipp/print
|
||||
existing_queue() {
|
||||
local i="$1" name="${P_NAME[$1]}" queue uri host rp
|
||||
host="$(lower "${AVAHI_HOST[$name]:-}")"
|
||||
rp="${AVAHI_RP[$name]:-}"
|
||||
for queue in "${!QUEUE_URI[@]}"; do
|
||||
uri="${QUEUE_URI[$queue]}"
|
||||
if [ "$uri" = "${P_URI[i]}" ]; then
|
||||
echo "$queue"
|
||||
return 0
|
||||
fi
|
||||
if [ -n "$host" ] && [[ "$uri" =~ ^ipps?://([^/:]+)(:[0-9]+)?/(.*)$ ]]; then
|
||||
local uri_host uri_path="${BASH_REMATCH[3]}"
|
||||
uri_host="$(lower "${BASH_REMATCH[1]}")"
|
||||
if { [ "$uri_host" = "$host" ] || [ "$uri_host" = "${AVAHI_ADDR[$name]:-}" ]; } \
|
||||
&& [ "$uri_path" = "$rp" ]; then
|
||||
echo "$queue"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# "HP LaserJet MFP M234dw (3BE90A) @ lab" -> HP_LaserJet_MFP_M234dw_3BE90A_lab
|
||||
queue_name() {
|
||||
local q="${1// @ /_}"
|
||||
q="$(sed -E 's/[^A-Za-z0-9_-]/_/g; s/_+/_/g; s/^_+//; s/_+$//' <<< "$q")"
|
||||
echo "${q:0:127}"
|
||||
}
|
||||
|
||||
# A name no other queue has, adding _2, _3... if needed
|
||||
declare -A TAKEN=()
|
||||
for queue in "${!QUEUE_URI[@]}"; do TAKEN["$queue"]=1; done
|
||||
unique_queue_name() {
|
||||
local base n=2 name
|
||||
base="$(queue_name "$1")"
|
||||
name="$base"
|
||||
while [ -n "${TAKEN[$name]:-}" ]; do
|
||||
name="${base:0:120}_$n"
|
||||
n=$((n + 1))
|
||||
done
|
||||
TAKEN["$name"]=1
|
||||
echo "$name"
|
||||
}
|
||||
|
||||
P_EXISTING=()
|
||||
for i in "${!P_NAME[@]}"; do
|
||||
P_EXISTING[i]="$(existing_queue "$i" || true)"
|
||||
done
|
||||
|
||||
# --- Choose ---------------------------------------------------------------------
|
||||
|
||||
# Chosen unless told otherwise: printers without a queue that aren't a shared
|
||||
# copy of a direct one
|
||||
defaults=()
|
||||
for i in "${!P_NAME[@]}"; do
|
||||
if [ -z "${P_EXISTING[i]}" ] && [ -z "${P_DUP[i]}" ]; then
|
||||
defaults+=("$((i + 1))")
|
||||
fi
|
||||
done
|
||||
|
||||
echo
|
||||
echo "Printers on your network:"
|
||||
for i in "${!P_NAME[@]}"; do
|
||||
if [ -n "${P_SHARER[i]}" ]; then how="shared by ${P_SHARER[i]}"; else how="direct"; fi
|
||||
note=""
|
||||
if [ -n "${P_EXISTING[i]}" ]; then
|
||||
note="already set up as ${P_EXISTING[i]}"
|
||||
elif [ -n "${P_DUP[i]}" ]; then
|
||||
note="same printer as $((P_DUP[i] + 1)), reached directly"
|
||||
fi
|
||||
printf ' %2d) %-46s %-20s %s\n' "$((i + 1))" "${P_NAME[i]}" "$how" "$note"
|
||||
done
|
||||
echo
|
||||
|
||||
chosen=()
|
||||
if $ALL; then
|
||||
chosen=("${defaults[@]}")
|
||||
else
|
||||
answer=""
|
||||
if [ ${#defaults[@]} -gt 0 ]; then
|
||||
read -rp "Add which printers? Numbers separated by spaces [${defaults[*]}], or n for none: " answer || answer=n
|
||||
answer="${answer:-${defaults[*]}}"
|
||||
else
|
||||
read -rp "Every printer is already set up. Add one anyway? Number, or Enter for none: " answer || answer=""
|
||||
fi
|
||||
for n in ${answer//,/ }; do
|
||||
[[ "$n" == [nN]* ]] && { chosen=(); break; }
|
||||
if [[ "$n" =~ ^[0-9]+$ ]] && (( n >= 1 && n <= ${#P_NAME[@]} )); then
|
||||
chosen+=("$n")
|
||||
else
|
||||
echo "Skipping \"$n\": not a number from the list."
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# --- Step 4: add queues ---------------------------------------------------------
|
||||
|
||||
ADDED=() SKIPPED=() FAILED=()
|
||||
|
||||
add_queue() {
|
||||
local i="$1" name="${P_NAME[$1]}" queue out fallback=""
|
||||
if [ -n "${P_EXISTING[i]}" ]; then
|
||||
SKIPPED+=("$name (already set up as ${P_EXISTING[i]})")
|
||||
return 0
|
||||
fi
|
||||
queue="$(unique_queue_name "$name")"
|
||||
echo "Adding $name as $queue..."
|
||||
if $DRY_RUN; then
|
||||
run sudo lpadmin -p "$queue" -E -v "${P_URI[i]}" -m everywhere
|
||||
ADDED+=("$queue")
|
||||
return 0
|
||||
fi
|
||||
|
||||
# lpadmin warns that printer drivers are deprecated; only its status counts
|
||||
if out="$(sudo lpadmin -p "$queue" -E -v "${P_URI[i]}" -m everywhere 2>&1)"; then
|
||||
ADDED+=("$queue")
|
||||
return 0
|
||||
fi
|
||||
|
||||
# The printer's address and path from Avahi instead of its mDNS name
|
||||
if [ -n "${AVAHI_ADDR[$name]:-}" ]; then
|
||||
fallback="ipp://${AVAHI_ADDR[$name]}:${AVAHI_PORT[$name]:-631}/${AVAHI_RP[$name]:-ipp/print}"
|
||||
echo " That didn't work; trying $fallback"
|
||||
if out="$(sudo lpadmin -p "$queue" -E -v "$fallback" -m everywhere 2>&1)"; then
|
||||
ADDED+=("$queue")
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
unset 'TAKEN[$queue]'
|
||||
FAILED+=("$name: $(tail -n1 <<< "$out")")
|
||||
}
|
||||
|
||||
for n in "${chosen[@]}"; do
|
||||
add_queue "$((n - 1))"
|
||||
done
|
||||
|
||||
# --- Step 5: default, check and summary ---------------------------------------
|
||||
|
||||
if [ -z "$DEFAULT" ] && ! $ALL && ! $DRY_RUN && [ ${#ADDED[@]} -gt 0 ]; then
|
||||
current="$(LC_ALL=C lpstat -d 2> /dev/null | sed -n 's/^system default destination: //p')"
|
||||
read -rp "Make one of the new printers the default? ${ADDED[*]} (Enter to leave it${current:+ as $current}): " DEFAULT || DEFAULT=""
|
||||
fi
|
||||
if [ -n "$DEFAULT" ]; then
|
||||
if [ -n "${QUEUE_URI[$DEFAULT]:-}" ] || [[ " ${ADDED[*]} " == *" $DEFAULT "* ]]; then
|
||||
run sudo lpadmin -d "$DEFAULT"
|
||||
else
|
||||
FAILED+=("default printer: there's no queue named $DEFAULT")
|
||||
DEFAULT=""
|
||||
fi
|
||||
fi
|
||||
|
||||
if ! $DRY_RUN; then
|
||||
ready=()
|
||||
for queue in "${ADDED[@]}"; do
|
||||
if LC_ALL=C lpstat -a "$queue" 2> /dev/null | grep -q "accepting requests"; then
|
||||
ready+=("$queue")
|
||||
if $PRINT_TEST; then
|
||||
lp -d "$queue" "$TEST_PAGE" > /dev/null || FAILED+=("$queue: the test page wasn't sent")
|
||||
fi
|
||||
else
|
||||
FAILED+=("$queue: added, but it isn't accepting jobs (see lpstat -t)")
|
||||
fi
|
||||
done
|
||||
ADDED=("${ready[@]}")
|
||||
fi
|
||||
|
||||
echo
|
||||
if $DRY_RUN; then echo "Would add:"; else echo "Added:"; fi
|
||||
[ ${#ADDED[@]} -gt 0 ] && printf ' %s\n' "${ADDED[@]}" || echo " none"
|
||||
if [ ${#SKIPPED[@]} -gt 0 ]; then
|
||||
echo "Skipped:"
|
||||
printf ' %s\n' "${SKIPPED[@]}"
|
||||
fi
|
||||
if [ ${#FAILED[@]} -gt 0 ]; then
|
||||
echo "Failed:"
|
||||
printf ' %s\n' "${FAILED[@]}"
|
||||
echo "A printer that can't be added without a driver needs its maker's: hplip for HP,"
|
||||
echo "printer-driver-brlaser for Brother lasers. This script doesn't install drivers."
|
||||
fi
|
||||
[ -n "$DEFAULT" ] && echo "Default printer: $DEFAULT"
|
||||
if [ ${#ADDED[@]} -gt 0 ] && ! $DRY_RUN; then
|
||||
$PRINT_TEST && echo "A test page was sent to each new printer."
|
||||
echo "Quit and reopen apps that are open (browsers especially) to see the new printers."
|
||||
fi
|
||||
|
||||
# Without its CUPS backend, the GTK dialog can't list printers at all
|
||||
if compgen -G '/usr/lib/*/gtk-3.0/*/printbackends' > /dev/null \
|
||||
&& ! compgen -G '/usr/lib/*/gtk-3.0/*/printbackends/libprintbackend-cups.so' > /dev/null; then
|
||||
echo "GTK's CUPS print backend is missing; reinstall it: sudo apt install --reinstall libgtk-3-0t64"
|
||||
fi
|
||||
|
||||
[ ${#FAILED[@]} -eq 0 ]
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Purpose : Mount a folder from another machine over SFTP (sshfs) and stay in
|
||||
# the foreground until it's unmounted. A systemd user service that
|
||||
# `configure storage` writes runs it at login.
|
||||
#
|
||||
# It runs as you, not root, so it can use your SSH keys: Bitwarden's SSH agent
|
||||
# while Bitwarden is running it, otherwise the keyring's, which Pop!_OS starts
|
||||
# with your session. It never asks for a password, so the server has to
|
||||
# accept one of those keys.
|
||||
#
|
||||
# Usage: sftp-mount <user@host:path> <mount point>
|
||||
|
||||
if [ $# -ne 2 ]; then
|
||||
echo "Usage: sftp-mount <user@host:path> <mount point>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ -S "$HOME/.bitwarden-ssh-agent.sock" ]; then
|
||||
export SSH_AUTH_SOCK="$HOME/.bitwarden-ssh-agent.sock"
|
||||
elif [ -S "${XDG_RUNTIME_DIR:-/run/user/$UID}/keyring/ssh" ]; then
|
||||
export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$UID}/keyring/ssh"
|
||||
elif [ -S "${XDG_RUNTIME_DIR:-/run/user/$UID}/gcr/ssh" ]; then
|
||||
export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$UID}/gcr/ssh"
|
||||
fi
|
||||
|
||||
# A mount left behind by a crash would make sshfs fail
|
||||
mountpoint -q "$2" && fusermount3 -u "$2"
|
||||
|
||||
# reconnect and ServerAlive* bring it back after the network drops (e.g.
|
||||
# suspend); idmap=user shows your files on the server as yours here
|
||||
exec sshfs -f "$1" "$2" \
|
||||
-o reconnect,ServerAliveInterval=15,ServerAliveCountMax=3 \
|
||||
-o BatchMode=yes,ConnectTimeout=15,idmap=user
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Back up your home folder to your Nextcloud files
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=%h/.local/share/federated-connector/connector/system/backup
|
||||
# Stay out of the way of whatever you're doing
|
||||
Nice=19
|
||||
IOSchedulingClass=idle
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Back up your home folder daily
|
||||
|
||||
[Timer]
|
||||
OnCalendar=daily
|
||||
RandomizedDelaySec=1h
|
||||
# Catch up at the next login if the computer was off or you weren't logged in
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Pause a Core's email when the mail server stops taking its password
|
||||
PartOf=graphical-session.target
|
||||
After=graphical-session.target
|
||||
# Only for those who've set up a Core (configure core starts it then)
|
||||
ConditionPathExistsGlob=%h/.config/federated-connector/cores/*.conf
|
||||
|
||||
[Service]
|
||||
ExecStart=%h/.local/share/federated-connector/connector/system/email-watch
|
||||
Restart=on-failure
|
||||
RestartSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=graphical-session.target
|
||||
Reference in New Issue
Block a user