#!/bin/sh
#
# blowfishctl -- install and run a BlowfishCMS site on OpenBSD.
#
# Run as root (doas). Commands:
#
#   blowfishctl install --domain example.org [--alias www.example.org]
#                       --admin USER [--mail-from ADDRESS]
#       Set up a new site from an unpacked release (run it from there:
#       doas ./bin/blowfishctl install ...). Installs the packages, creates
#       the service accounts and folders, writes the site's settings file,
#       builds the catalogue, starts the services, configures httpd, gets a
#       Let's Encrypt certificate and schedules its renewal.
#   blowfishctl update [--check] [--skip-tests] RELEASE.tar.gz
#       Install a new release: checks and tests it against a copy of the
#       catalogue, snapshots the catalogue, migrates it, swaps the code in,
#       restarts the services and checks the site; puts the old code back if
#       anything fails. --check stops after the tests.
#   blowfishctl rollback        put back the code from before the last update
#   blowfishctl releases        list the kept releases
#   blowfishctl status          services, certificate, disk, memory and release
#   blowfishctl restart         restart the site's services
#   blowfishctl httpd           rewrite httpd's configuration for this site
#                               (update does this)
#   blowfishctl password [NAME] set an admin user's password (asked for, not
#                               echoed) and end their sessions; a NAME that
#                               isn't a user yet becomes an owner
#   blowfishctl unlock          clear failed sign-ins (after a lockout)
#   blowfishctl mail-token      set the Postmark server token (asked for)
#   blowfishctl certificate     get or renew the TLS certificate, then
#                               switch httpd to HTTPS (used by install and cron)
#   blowfishctl migrate         update the catalogue's tables (update does this)
#   blowfishctl addon list | add FILE.tar.gz | refresh | install NAME | update NAME | update --all
#   blowfishctl addon enable NAME | disable NAME | remove NAME
#       Optional features (owners can do all of this on the Add-ons screen
#       too). add puts the add-ons in an archive in the site's list (only
#       for code you trust); refresh fetches the archive at the server's
#       address, when it has one. install and update put an add-on from the
#       list in /opt/blowfishcms-addons, which updates leave alone;
#       enable/disable switch one on or off (an add-on with its own service
#       also gets an account, private folders and httpd addresses). update
#       --all updates every installed add-on that has a newer version, one
#       at a time (one that fails keeps its version; the rest carry on).
#   blowfishctl theme list | add FILE.tar.gz | refresh | install NAME | update NAME | update --all | remove NAME
#       Themes, the same way (owners can do this on the Themes tab too).
#       Each is a folder in /opt/blowfishcms-themes; Modern comes with the
#       release. Removing one deletes its variants.
#   blowfishctl updates-from [URL | none]
#       Where updates come from: a Repositories add-on's address, such as
#       https://example.org/x/repos/ (its blowfishcms repository's newest
#       release, and its blowfishcms-addons and blowfishcms-themes archives).
#       Without an argument, shows it; none stops looking for updates.
#       Owners can set it on the System screen too.
#   blowfishctl check-updates
#       Look for a new BlowfishCMS release (where updates come from), and
#       newer versions of the add-ons and themes installed; email the alerts
#       address set on the Mail screen about anything new. The nightly job
#       does this.
#   blowfishctl places
#       Fetch the city database Analytics looks visitors' places up in
#       (DB-IP's free IP to City Lite, monthly). The nightly job does this
#       once a month; only the place is kept, never the address.
#   blowfishctl update latest
#       Fetch the newest release from where updates come from, check its
#       sha256, and update.
#   blowfishctl mfa-off NAME
#       Turn off two-step sign-in for an admin user who has lost their phone
#       and recovery codes; their password alone signs them in again.
#   blowfishctl nightly
#       The nightly backup (root's crontab runs it): keeps the newest of its
#       own backups, as many as the System screen says (14 to begin with).
#   blowfishctl requests
#       Carry out what owners asked for on the System screen (update, roll
#       back, back up), and pass add-ons' mail and videos (Live's saved
#       streams) on. Root's crontab runs it every minute.
#   blowfishctl files
#       Copy the site's own files from /opt/blowfishcms-files into the web
#       root (a resume, a verification file, a PGP key: anything served as it
#       is). /opt/blowfishcms-files/cv/me.pdf is served at /cv/me.pdf. Updates
#       keep them; a file can't replace one of the code's.
#   blowfishctl backup [--with-secrets]
#       Write a backup archive to /var/backups/blowfishcms (media, catalogue
#       and comments snapshots, settings, code). --with-secrets also writes
#       a separate archive with the token and keys.
#

# How this script is put together: the settings just below name every folder
# and file the site uses; then come small helpers, then the pieces each
# command is built from (accounts, folders, httpd, certificates, cron,
# updates, add-ons, themes, requests, backups), and at the very bottom the
# `case $cmd in` that picks the command. It's POSIX sh (OpenBSD's ksh runs
# it), runs as root, and must stay shellcheck-clean.
#
# set -e: stop at the first command that fails. set -u: using a variable
# that was never set is an error (so a typo can't turn "rm -rf $DIR/x" into
# "rm -rf /x"). umask 022: new files are readable by all, writable by root.
# PATH is set explicitly so only the system's own programs are run.
set -eu
umask 022
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/usr/local/bin
export PATH

# ---- Layout (one site per server) ------------------------------------------
NAME=blowfishcms
APP=/opt/$NAME                          # the code (a release)
CHROOT=/var/www                         # httpd's chroot; paths below are inside it
WEB=$CHROOT/htdocs/$NAME                # public/ of the live release
DATA=$CHROOT/var/db/$NAME               # catalogue, admin keys and temp files
COMMENTS=$CHROOT/var/db/$NAME-comments  # comments and likes
CONTACT=$CHROOT/var/db/$NAME-contact    # contact form rate file and log
MEDIA=$CHROOT/media/$NAME               # uploaded media, served at /media/
SECRETS=$CHROOT/etc/$NAME               # Postmark token
SESSION=$CHROOT/etc/$NAME-session       # admin session key (services with admin screens)
STAFF=_bfstaff                          # group of the services that may read the session key
CONF=$CHROOT/etc/$NAME.conf             # the site's settings (read by the code)
DB=$DATA/catalog.sqlite
STORE=/var/backups/$NAME                # backups; releases/ holds old code
SYS=$DATA/system                        # the admin's System screen: requests and their results
ADDONS_EXTRA=/opt/$NAME-addons          # installed add-ons
SITE_FILES=/opt/$NAME-files            # the site's own files (a resume, a key), served as they are
THEMES_EXTRA=/opt/$NAME-themes          # installed themes
PLACES_URL=https://download.db-ip.com/free/dbip-city-lite-MONTH.mmdb.gz   # Analytics' city database, MONTH as 2026-11 (/etc/blowfishcms-places-url overrides it)
ADDON_DATA=$CHROOT/var/db/$NAME-addons  # each service add-on's data (its account)
ADDON_SECRETS=$CHROOT/etc/$NAME-addons  # each service add-on's keys (its account)
HTTPD_SITE=/etc/httpd.d/$NAME.conf
PACKAGES="p5-CGI p5-DBI p5-DBD-SQLite p5-GD p5-Text-Markdown p5-HTML-Scrubber p5-IO-Socket-SSL p5-FCGI libwebp python%3"   # python%3: OpenBSD's Python 3 (python3), which updates use to run the test suites before switching
# Services: name, account, workers, what it serves.
SERVICES="public admin contact comments"
KEEP=5

# die MESSAGE: print an error and stop. log MESSAGE: print progress (both to
# standard error, so standard output stays clean for values).
die() { echo "blowfishctl: error: $*" >&2; exit 1; }
log() { echo "blowfishctl: $*" >&2; }
# The help text is the comment block at the top of this file (line 3 on, up
# to the first line that isn't a comment).
usage() { awk 'NR > 2 && /^#/ {sub(/^# ?/, ""); print; next} NR > 2 {exit}' "$0"; }
account() { echo "_bf$1"; }                       # public -> _bfpublic
service() { echo "blowfish_$1"; }                 # public -> blowfish_public
socket() { echo "$CHROOT/run/blowfish-$1.sock"; }
workers() { case $1 in public) echo 3 ;; admin|comments) echo 2 ;; *) echo 1 ;; esac; }
# conf_get KEY: one value from the site's settings file (key = value).
conf_get() { sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" "$CONF" 2>/dev/null | sed 's/[[:space:]]*$//' | head -1; }
# as_user ACCOUNT COMMAND: runs a command as one of the service accounts
# (they have no login shell, so su is told to use /bin/sh).
as_user() { u=$1; shift; su -s /bin/sh "$u" -c "$*"; }

[ "$(id -u)" -eq 0 ] || die "must run as root (try: doas sh $0 ${1:-}; on a new server without doas set up, become root with su - and run sh $0 ${1:-})"
[ "$(uname -s)" = OpenBSD ] || die "BlowfishCMS runs on OpenBSD"

# ---- Pieces shared by the commands -----------------------------------------

# A free id below 1000 (system accounts), the same for the user and its group.
# The first unused user and group id from 850, so new accounts never clash.
free_id() {
	id=850
	while grep -q "^[^:]*:[^:]*:$id:" /etc/passwd /etc/group; do id=$((id + 1)); done
	echo "$id"
}
# Makes a service account (no home, no login) and its group if missing.
ensure_account() {   # ensure_account NAME PRIMARY-GROUP(or same)
	user=$1 group=$2
	if ! grep -q "^$group:" /etc/group; then
		groupadd -g "$(free_id)" "$group"
	fi
	if ! id "$user" >/dev/null 2>&1; then
		useradd -u "$(free_id)" -g "$group" -c "BlowfishCMS $user" -d /var/empty -s /sbin/nologin -L daemon "$user"
		log "  account $user (group $group)"
	fi
}
# The four core service accounts and the staff group.
accounts() {
	ensure_account "$(account public)" "$(account public)"
	ensure_account "$(account admin)" "$(account admin)"
	# The other services share the public group, which may read the catalogue
	# (the contact form needs its address, the comments service the articles).
	# The services drop to their primary group only, as slowcgi does.
	ensure_account "$(account contact)" "$(account public)"
	ensure_account "$(account comments)" "$(account public)"
	grep -q "^$STAFF:" /etc/group || groupadd -g "$(free_id)" "$STAFF"
}
# The services with admin screens keep the staff group, to read the session key.
staff_service() { case $1 in admin|comments|contact|x*) return 0 ;; *) return 1 ;; esac; }
# Sign-in through the admin's login page: the session key (readable by the
# staff group, replaceable by the admin service for "sign out everywhere").
# Prints "changed" when it set something up for the first time.
# The admin session key: made once (random), owned by the admin account,
# readable by the staff group.
session_setup() {
	adm=$(account admin)
	grep -q "^$STAFF:" /etc/group || { groupadd -g "$(free_id)" "$STAFF"; echo changed; }
	install -d -o "$adm" -g "$STAFF" -m 0750 "$SESSION"
	if [ ! -s "$SESSION/session.key" ]; then
		openssl rand -hex 32 >"$SESSION/session.key"
		echo changed
	fi
	chown "$adm:$STAFF" "$SESSION/session.key"; chmod 0640 "$SESSION/session.key"
}
# Every folder the site needs, each owned by the account that writes it and
# readable by those that read it (install -d sets owner, group and mode in
# one go). Also the admin's CSRF key.
folders() {
	pub=$(account public) adm=$(account admin) con=$(account contact) com=$(account comments)
	install -d -o "$adm" -g "$pub" -m 0750 "$DATA"
	install -d -o "$adm" -g "$adm" -m 0700 "$DATA/admin" "$DATA/admin/tmp"
	[ -s "$DATA/admin/csrf.key" ] || { openssl rand -hex 32 >"$DATA/admin/csrf.key"; }
	chown "$adm:$adm" "$DATA/admin/csrf.key"; chmod 0600 "$DATA/admin/csrf.key"
	install -d -o "$com" -g "$pub" -m 0755 "$COMMENTS"
	install -d -o "$com" -g "$pub" -m 0700 "$COMMENTS/private"
	install -d -o "$con" -g "$pub" -m 0700 "$CONTACT"
	install -d -o root -g wheel -m 0755 "$CHROOT/media"
	[ -d "$CHROOT/htdocs" ] || install -d -o root -g daemon -m 0755 "$CHROOT/htdocs"
	install -d -o "$adm" -g www -m 0755 "$MEDIA"
	media_folders
	install -d -o "$con" -g "$pub" -m 0700 "$SECRETS"
	install -d -o root -g wheel -m 0755 "$CHROOT/run" "$CHROOT/acme" "$STORE"
	chmod 0700 "$STORE"
}

# Copy a release tree into $2 with root ownership and the right modes.
# Copies a release into place: root owns everything, folders 0755, files
# 0644, scripts executable. The services can read the code but not change it.
place_code() {
	src=$1 dst=$2
	rm -rf "$dst"
	# (A fresh OpenBSD has no /opt.)
	install -d -o root -g wheel -m 0755 "$(dirname "$dst")"
	cp -R "$src" "$dst"
	rm -rf "$dst/.git"
	chown -R root:wheel "$dst"
	find "$dst" -type d -exec chmod 0755 {} +
	find "$dst" -type f -exec chmod 0644 {} +
	for f in "$dst"/cgi-bin/*.pl "$dst"/bin/* "$dst"/tests/*.py "$dst"/tests/*.pl; do
		[ -f "$f" ] && chmod 0755 "$f"
	done
	return 0
}
# Builds the web root httpd serves: the release's public/, each add-on's
# public/ at /addons/NAME/ and each theme's assets/ at /themes/NAME/, then
# the compressed copies and the site's own files.
build_web() {   # build_web CODE-DIR WEB-DIR: public/, each add-on's public/ at /addons/NAME/, each theme's assets/ at /themes/NAME/
	rm -rf "$2"; cp -Rp "$1/public" "$2"
	install -d -m 0755 "$2/addons" "$2/themes"
	for d in "$ADDONS_EXTRA"/*/public; do
		[ -d "$d" ] || continue
		bn=$(basename "$(dirname "$d")")
		[ -e "$2/addons/$bn" ] || cp -Rp "$d" "$2/addons/$bn"
	done
	for d in "$1"/themes/*/assets "$THEMES_EXTRA"/*/assets; do
		[ -d "$d" ] || continue
		bn=$(basename "$(dirname "$d")")
		[ -e "$2/themes/$bn" ] || cp -Rp "$d" "$2/themes/$bn"
	done
	precompress "$2"
	site_files "$2"
}
# Compressed copies of the code's text files, which httpd sends to browsers
# that accept them (gzip-static): CSS and JavaScript shrink by about 70%.
precompress() {   # precompress WEB-DIR
	for d in css js addons themes assets; do
		[ -d "$1/$d" ] || continue
		find "$1/$d" -type f \( -name '*.css' -o -name '*.js' -o -name '*.svg' \) | while IFS= read -r f; do
			gzip -9 -n -c "$f" >"$f.gz" && chmod 0644 "$f.gz"
		done
	done
}
# The site's own files go in next to the release's, never over them, and never
# into /addons/, /assets/ or a hidden name.
site_files() {   # site_files WEB-DIR
	[ -d "$SITE_FILES" ] || return 0
	(cd "$SITE_FILES" && find . -type f ! -path '*/.*' | sed 's|^\./||') | while IFS= read -r f; do
		case $f in addons/*|assets/*|css/*|js/*|themes/*) log "site file $f skipped (that folder belongs to the code)"; continue ;; esac
		if [ -e "$1/$f" ]; then log "site file $f skipped (the code has a file of that name)"; continue; fi
		install -d -m 0755 "$1/$(dirname "$f")"
		install -m 0644 "$SITE_FILES/$f" "$1/$f"
	done
}
# Add-ons that are on: "NAME KIND" lines (KIND is service or -). Empty before the
# catalogue exists.
# addons_on [CODE-DIR]: the add-ons that are on and usable, one per line:
# NAME KIND FILES (KIND is "service" or "-", FILES is "files" or "-"), as
# site.pl --addons reports them.
addons_on() {
	as_user "$(account admin)" "/usr/bin/perl '${1:-$APP}/cgi-bin/site.pl' --addons" 2>/dev/null | awk -F '\t' '$2 == "on" && $4 == "ok" {print $1, $3, ($5 == "" ? "-" : $5)}' || true
}
# Every service: the core ones and those of add-ons that run their own (xNAME).
# Every service to run: the four core ones plus xNAME for each add-on that
# runs as its own service.
all_services() {
	echo "$SERVICES"
	addons_on "${1:-}" | awk '$2 == "service" {print "x" $1}'
}
# "tls" once the site has a certificate, else "plain".
httpd_mode() { if [ -f "/etc/ssl/$(conf_get domain).fullchain.pem" ]; then echo tls; else echo plain; fi; }

# This command, and its manual page (man blowfishctl), from a release.
install_tool() {   # install_tool CODE-DIR
	install -o root -g wheel -m 0555 "$1/bin/blowfishctl" /usr/local/sbin/blowfishctl
	[ -f "$1/man/blowfishctl.8" ] || return 0
	install -d -o root -g wheel -m 0755 /usr/local/man/man8
	install -o root -g bin -m 0444 "$1/man/blowfishctl.8" /usr/local/man/man8/blowfishctl.8
	# Add it to man -k's index, when there is one.
	if [ -f /usr/local/man/mandoc.db ]; then makewhatis -d /usr/local/man /usr/local/man/man8/blowfishctl.8 2>/dev/null || true; fi
}
# The files of a release: present, no symlinks, Unix line endings.
check_files() {   # check_files DIR
	r=$1
	[ -f "$r/cgi-bin/site.pl" ] && [ -f "$r/bin/blowfish-fcgi" ] && [ -d "$r/public" ] || die "$r is not a BlowfishCMS release"
	if find "$r" -type l | grep -q .; then die "the release contains symlinks"; fi
	crlf=$(find "$r" -type f \( -name '*.pl' -o -name '*.pm' -o -name '*.t' -o -name '*.py' -o -path "$r/bin/*" -o -path "$r/openbsd/*" \) \
		-exec grep -l "$(printf '\r')" {} + 2>/dev/null || true)
	[ -z "$crlf" ] || die "Windows (CRLF) line endings in: $(echo "$crlf" | sed "s|$r/||g" | tr '\n' ' ')"
}
# ...and that it compiles (needs the Perl packages installed).
# ...and that it compiles (perl -c), and its starter pages and themes are
# valid JSON. A broken release is refused before anything changes.
check_release() {   # check_release DIR
	r=$1
	check_files "$r"
	for f in cgi-bin/site.pl bin/blowfish-fcgi; do
		perl -c -I"$r/lib" "$r/$f" >/dev/null 2>&1 || { perl -c -I"$r/lib" "$r/$f"; die "$f does not compile"; }
	done
	perl -MJSON::PP -e 'for (@ARGV) {local $/; open my $f, "<:raw", $_ or die "$_\n"; JSON::PP->new->decode(<$f>)}' \
		"$r/content/starter-pages.json" "$r"/themes/*/theme.json || die "a content file is not valid JSON"
}

# Copies an SQLite database safely while it's in use, with SQLite's own
# backup function (copying the file directly could catch it half-written),
# then checks the copy is intact. Waits up to 15 s for a busy database.
snapshot_db() {   # snapshot_db SOURCE DEST (SQLite backup API, then integrity check)
	[ -f "$1" ] || return 0
	perl -MDBI -e '
		my $s = DBI->connect("dbi:SQLite:dbname=$ARGV[0]", "", "", {RaiseError => 1});
		$s->sqlite_busy_timeout(15000);
		$s->sqlite_backup_to_file($ARGV[1]);
		my $d = DBI->connect("dbi:SQLite:dbname=$ARGV[1]", "", "", {RaiseError => 1});
		my ($r) = $d->selectrow_array("PRAGMA integrity_check");
		die "integrity_check: $r\n" unless $r eq "ok";
	' "$1" "$2"
	chmod 0600 "$2"
}

media_folders() {   # one per library; a release that adds a library adds its folder (httpd runs this on every update)
	adm=$(account admin)
	for kind in photography pictures music artwork blog video file site; do
		[ -d "$MEDIA/$kind" ] || install -d -o "$adm" -g www -m 0755 "$MEDIA/$kind"
	done
}

analytics_folder() {   # visitor numbers, kept by the comments service and readable by it alone
	[ -d "$COMMENTS" ] || return 0
	com=$(account comments)
	install -d -o "$com" -g "$(account public)" -m 0700 "$COMMENTS/analytics"
}

# Updates the catalogue's tables with a release's code, as the admin account
# (which owns the catalogue), then the comments database as the comments
# account. Every install and update runs this before switching code.
migrate_with() {   # migrate_with CODE-DIR: schema changes as the catalogue's owner
	analytics_folder
	as_user "$(account admin)" "/usr/bin/perl '$1/cgi-bin/site.pl' --migrate" >&2
	if [ -f "$COMMENTS/comments.sqlite" ] || [ -n "${FRESH:-}" ]; then
		as_user "$(account comments)" "/usr/bin/perl '$1/cgi-bin/site.pl' --comments-init" >&2
	fi
}

# Installs the rc.d script for each service and sets its flags: which account
# it runs as, its socket, the request time limit (600 s), its worker count,
# and -G for the services that may read the session key.
services_install() {   # services_install [SERVICE...] (default: all)
	# shellcheck disable=SC2046
	[ $# -gt 0 ] || set -- $(all_services)
	for s in "$@"; do
		svc=$(service "$s")
		install -o root -g wheel -m 0555 "$APP/openbsd/rc.d/blowfish_fcgi" "/etc/rc.d/$svc"
		rcctl enable "$svc" >/dev/null
		extra=''; if staff_service "$s"; then extra=" -G $STAFF"; fi
		rcctl set "$svc" flags "-u $(account "$s") -p / -s $(socket "$s") -t 600 -w $(workers "$s")$extra"
	done
}
# Restarts every service; returns non-zero if any failed to start.
restart_services() {
	rs=0
	for s in $(all_services); do
		svc=$(service "$s")
		if rcctl restart "$svc" >/dev/null; then log "  restarted $svc"; else log "  $svc failed to start"; rs=1; fi
	done
	return $rs
}

# The site's address, from the settings file.
site_url() { echo "https://$(conf_get domain)"; }
# After an update: fetches a few addresses every site has (and the feed if
# Blog is on). Any failure makes the update put the old code back.
smoke_test() {
	fail=0 url=$(site_url)
	for p in / /themes.css /css/site.css /js/theme.js /robots.txt /sitemap.xml; do
		if ftp -V -o /dev/null "$url$p" >/dev/null 2>&1; then log "  ok    $p"; else log "  FAIL  $p"; fail=1; fi
	done
	# The feed only exists while the Blog page is on (the sitemap lists the pages that are).
	if ftp -V -o - "$url/sitemap.xml" 2>/dev/null | grep -q "<loc>$url/blog/</loc>"; then
		if ftp -V -o /dev/null "$url/blog/feed.xml" >/dev/null 2>&1; then log "  ok    /blog/feed.xml"; else log "  FAIL  /blog/feed.xml"; fail=1; fi
	else
		log "  skip  /blog/feed.xml (the Blog page is off)"
	fi
	return $fail
}

# ---- httpd -----------------------------------------------------------------
# The site's server blocks live in their own file, included from httpd.conf.
# "plain" serves HTTP only (enough for Let's Encrypt to verify the domain);
# "tls" redirects HTTP to HTTPS and serves the site over HTTPS.
# The httpd lines that pass a request to a service's socket, with the
# SCRIPT_NAME marker the app reads (see dispatch() in lib/BlowfishCMS.pm).
fastcgi_block() {   # fastcgi_block SERVICE SCRIPT_NAME
	cat <<EOF
        fastcgi {
            socket "/run/blowfish-$1.sock"
            param SCRIPT_FILENAME "$APP/cgi-bin/site.pl"
            param SCRIPT_NAME "$2"
        }
EOF
}
# The httpd locations for add-ons that are on: /x/NAME/files/ served straight
# from disk (for "files" add-ons), /x/NAME/... to the add-on's service (or the
# public one), and /admin/x/NAME/... for add-ons with their own service.
addon_locations() {   # add-on addresses: /x/NAME/... and, for service add-ons, /admin/x/NAME/...
	addons_on | while read -r n kind files; do
		if [ "$kind" = service ]; then svc=x$n; else svc=public; fi
		# Files the add-on writes and httpd serves as they are (Live's stream pieces).
		if [ "$files" = files ]; then
			echo "    location \"/x/$n/files/*\" {"
			echo "        root \"${ADDON_DATA#"$CHROOT"}/$n-files\""
			echo "        request strip 3"
			echo "        header set Cache-Control \"no-cache\" always"
			echo "    }"
		fi
		echo "    location \"/x/$n/*\" {"
		fastcgi_block "$svc" /_addon
		echo "    }"
		[ "$kind" = service ] || continue
		echo "    location \"/admin/x/$n/*\" {"
		echo "        header set X-Robots-Tag \"noindex, nofollow\" always"
		echo "        header set Cache-Control \"no-store\" always"
		fastcgi_block "$svc" /_addon
		echo "    }"
	done
}
# The served folders of add-ons with "files": owned by the add-on's account, readable by httpd.
# The served folders of "files" add-ons: written by the add-on's account,
# readable by httpd (group www).
addon_files_dirs() {
	addons_on | while read -r n kind files; do
		[ "$kind" = service ] && [ "$files" = files ] || continue
		install -d -o "$(account "x$n")" -g www -m 0750 "$ADDON_DATA/$n-files"
	done
}
# Media types for live streams: an add-on with "files" (Live) has httpd
# serve an HLS playlist (.m3u8) and its pieces (.m4s, and .mp4 for the first)
# as they are. iPhones play a stream only when each comes with its proper
# type, and /usr/share/misc/mime.types may not have them all. httpd refuses
# a type named twice, so only the ones it lacks are added, and only when
# /etc/httpd.conf takes the rest from mime.types (a types block of ours would
# otherwise replace httpd's built-in ones).
stream_types() {
	[ -n "$(addons_on | awk '$3 == "files"')" ] || return 0
	grep -q 'include "/usr/share/misc/mime.types"' /etc/httpd.conf 2>/dev/null || return 0
	missing=''
	for t in application/vnd.apple.mpegurl:m3u8 video/iso.segment:m4s video/mp4:mp4; do
		grep -Eq "^[^#]*[[:space:]]${t#*:}([[:space:];]|\$)" /usr/share/misc/mime.types 2>/dev/null || missing="$missing $t"
	done
	[ -n "$missing" ] || return 0
	echo "types {"
	for t in $missing; do echo "    ${t%%:*} ${t#*:}"; done
	echo "}"
}
# Writes the site's whole httpd configuration. In order: port 80 (Let's
# Encrypt's check, and a redirect to HTTPS once there's a certificate),
# aliases redirecting to the main domain, then the HTTPS server with its
# security headers (the content security policy allows nothing from other
# sites and no inline scripts or styles). httpd uses the FIRST location that
# matches, so the order of the locations below is what routes each address
# to the right service: specific addresses first (contact, add-ons,
# comments, likes, downloads, analytics, mail, admin), then blocks for
# scripts and hidden files, the download-only files folder, media, cached
# code files, and last the patterns for pages (/name/) and item pages
# (/kind/id/). tools/fakebsd/routes.py replays addresses through this to
# check each one lands where it should.
httpd_site() {   # httpd_site plain|tls
	mode=$1 domain=$(conf_get domain) aliases=$(conf_get aliases)
	echo "# BlowfishCMS: $domain. Written by blowfishctl; changes are overwritten."
	stream_types
	echo "server \"$domain\" {"
	for a in $aliases; do echo "    alias \"$a\""; done
	echo "    listen on * port 80"
	echo "    location \"/.well-known/acme-challenge/*\" {"
	echo "        root \"/acme\""
	echo "        request strip 2"
	echo "    }"
	if [ "$mode" = tls ]; then
		echo "    location \"*\" { block return 301 \"https://$domain\$REQUEST_URI\" }"
		echo "}"
		for a in $aliases; do
			echo "server \"$a\" {"
			echo "    listen on * tls port 443"
			echo "    tls {"
			echo "        certificate \"/etc/ssl/$domain.fullchain.pem\""
			echo "        key \"/etc/ssl/private/$domain.key\""
			echo "    }"
			echo "    location \"*\" { block return 301 \"https://$domain\$REQUEST_URI\" }"
			echo "}"
		done
		echo "server \"$domain\" {"
		echo "    listen on * tls port 443"
		echo "    tls {"
		echo "        certificate \"/etc/ssl/$domain.fullchain.pem\""
		echo "        key \"/etc/ssl/private/$domain.key\""
		echo "    }"
		echo "    hsts max-age 31536000"
		scheme=https
	else
		scheme=http
	fi
	cat <<EOF
    root "/htdocs/$NAME"
    directory index "index.html"
    connection max request body 270532608
    connection request timeout 300
    header set X-Content-Type-Options "nosniff"
    header set Referrer-Policy "strict-origin-when-cross-origin"
    header set Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()"
    header set Cross-Origin-Opener-Policy "same-origin"
    header set Content-Security-Policy "default-src 'self'; media-src 'self' blob:; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'$( [ "$mode" = tls ] && echo '; upgrade-insecure-requests')"
    gzip-static
    location "/contact/send" {
$(fastcgi_block contact /contact/send)
    }
$(addon_locations)
    location "/talk/comment" {
$(fastcgi_block comments /talk/comment)
    }
    location "/talk/like" {
$(fastcgi_block comments /talk/like)
    }
    location "/download/*" {
        header set X-Robots-Tag "noindex" always
$(fastcgi_block comments /_download)
    }
    location "/admin/comments/" {
        header set X-Robots-Tag "noindex, nofollow" always
        header set Cache-Control "no-store" always
$(fastcgi_block comments /admin/comments/)
    }
    location "/stats/hit" {
$(fastcgi_block comments /stats/hit)
    }
    location "/admin/analytics/" {
        header set X-Robots-Tag "noindex, nofollow" always
        header set Cache-Control "no-store" always
$(fastcgi_block comments /admin/analytics/)
    }
    location "/admin/mail/" {
        header set X-Robots-Tag "noindex, nofollow" always
        header set Cache-Control "no-store" always
$(fastcgi_block contact /admin/mail/)
    }
    location "/admin/" {
        header set X-Robots-Tag "noindex, nofollow" always
        header set Cache-Control "no-store" always
$(fastcgi_block admin /admin/)
    }
    location "/admin/comments" { block return 301 "$scheme://$domain/admin/comments/" }
    location "/admin/analytics" { block return 301 "$scheme://$domain/admin/analytics/" }
    location "/admin/mail" { block return 301 "$scheme://$domain/admin/mail/" }
    location "/admin" { block return 301 "$scheme://$domain/admin/" }
    location "/admin/*" { block return 404 }
EOF
	for route in / /themes.css /robots.txt /sitemap.xml /blog/feed.xml; do
		echo "    location \"$route\" {"
		fastcgi_block public "$route"
		echo "    }"
	done
	cat <<EOF
    location "/index.html" {
$(fastcgi_block public /)
    }
    location "*.pl*" { block return 404 }
    location "*.cgi*" { block return 404 }
    location "*.php*" { block return 404 }
    location "*/.*" { block return 404 }
    # Files to download: never shown as a page of the site, whatever they are.
    location "/media/file/*" {
        root "/media/$NAME"
        request strip 1
        no static-cache-control
        header set Cache-Control "public, max-age=86400"
        header set Content-Disposition "attachment"
        header set Content-Security-Policy "sandbox"
        header set X-Content-Type-Options "nosniff"
    }
    location "/media/*" {
        root "/media/$NAME"
        request strip 1
        no static-cache-control
        header set Cache-Control "public, max-age=2592000"
    }
$(static_cache)
    # Every page: /name/ (the site answers 404 if no page has it); /name adds the slash.
    location match "^/[%w-]+/$" {
$(fastcgi_block public /_page)
    }
    location match "^/[%w-]+$" { block return 301 "$scheme://$domain\$DOCUMENT_URI/" }
    # A library item's or a tag's page: /picture/ID/, /tags/NAME/ (the site answers 404 for anything else).
    location match "^/[%w-]+/[%w-]+/$" {
$(fastcgi_block public /_item)
    }
}
EOF
}
# Browsers keep the code's files: CSS and JavaScript (and add-ons' files) are
# linked with ?v=VERSION, so they can be kept for a year; theme files and
# built-in pictures for a day. Media file names are new for each upload.
# Cache headers for the code's files: /css/, /js/ and /addons/ for a year
# (their links carry ?v=, which changes with the file), themes and built-in
# pictures for a day.
static_cache() {
	for p in /css/ /js/ /addons/; do
		printf '    location "%s*" {\n        no static-cache-control\n        header set Cache-Control "public, max-age=31536000, immutable"\n        header set Vary "Accept-Encoding"\n    }\n' "$p"
	done
	for p in /themes/ /assets/; do
		printf '    location "%s*" {\n        no static-cache-control\n        header set Cache-Control "public, max-age=86400"\n        header set Vary "Accept-Encoding"\n    }\n' "$p"
	done
}
# Installs the new httpd configuration safely: if it's unchanged, nothing
# happens; otherwise the old file is kept, the new one is checked with
# `httpd -n`, and if the check fails the old one is put back. Then httpd is
# reloaded (or started).
httpd_apply() {   # httpd_apply plain|tls: write, check, reload; keeps the old file if the check fails
	install -d -o root -g wheel -m 0755 /etc/httpd.d
	new=$(mktemp /tmp/blowfish-httpd.XXXXXXXXXX)
	httpd_site "$1" >"$new"
	# Nothing to do when the file is already current (the daily renewal).
	if [ -f "$HTTPD_SITE" ] && cmp -s "$new" "$HTTPD_SITE" && grep -q "include \"$HTTPD_SITE\"" /etc/httpd.conf 2>/dev/null; then
		rm -f "$new"
		rcctl check httpd >/dev/null 2>&1 || rcctl start httpd >/dev/null
		return 0
	fi
	if [ ! -f /etc/httpd.conf ]; then
		printf 'types { include "/usr/share/misc/mime.types" }\n' >/etc/httpd.conf
	fi
	grep -q "include \"$HTTPD_SITE\"" /etc/httpd.conf || printf 'include "%s"\n' "$HTTPD_SITE" >>/etc/httpd.conf
	old=$(mktemp /tmp/blowfish-httpd-old.XXXXXXXXXX)
	[ -f "$HTTPD_SITE" ] && cp -p "$HTTPD_SITE" "$old"
	install -o root -g wheel -m 0644 "$new" "$HTTPD_SITE"
	rm -f "$new"
	if ! httpd -n >/dev/null 2>&1; then
		httpd -n || true
		if [ -s "$old" ]; then install -o root -g wheel -m 0644 "$old" "$HTTPD_SITE"; else rm -f "$HTTPD_SITE"; fi
		rm -f "$old"
		die "the new httpd configuration failed its check; the previous one is back"
	fi
	rm -f "$old"
	rcctl enable httpd >/dev/null
	if rcctl check httpd >/dev/null 2>&1; then rcctl reload httpd >/dev/null; else rcctl start httpd >/dev/null; fi
}

# ---- Certificates ----------------------------------------------------------
# Adds the site to acme-client's configuration (Let's Encrypt) if it isn't
# there yet, and checks it.
acme_conf() {
	domain=$(conf_get domain) aliases=$(conf_get aliases)
	[ -f /etc/acme-client.conf ] || : >/etc/acme-client.conf
	if ! grep -q '^authority letsencrypt' /etc/acme-client.conf; then
		cat >>/etc/acme-client.conf <<'EOF'
authority letsencrypt {
	api url "https://acme-v02.api.letsencrypt.org/directory"
	account key "/etc/acme/letsencrypt-privkey.pem"
}
EOF
	fi
	if ! grep -q "^domain $domain " /etc/acme-client.conf; then
		{
			echo "domain $domain {"
			[ -z "$aliases" ] || echo "	alternative names { $aliases }"
			echo "	domain key \"/etc/ssl/private/$domain.key\""
			echo "	domain full chain certificate \"/etc/ssl/$domain.fullchain.pem\""
			echo "	sign with letsencrypt"
			echo "}"
		} >>/etc/acme-client.conf
	fi
	acme-client -n >/dev/null || die "/etc/acme-client.conf failed its check"
}
# Gets or renews the certificate (acme-client exits 2 when it's still
# current, which is fine), then switches httpd to HTTPS.
certificate() {
	domain=$(conf_get domain)
	acme_conf
	install -d -o root -g wheel -m 0700 /etc/acme
	# acme-client exits 2 when the certificate is still current.
	rc=0; acme-client -v "$domain" >&2 || rc=$?
	[ "$rc" -eq 0 ] || [ "$rc" -eq 2 ] || return 1
	httpd_apply tls
	# A renewed certificate is picked up on reload.
	[ "$rc" -ne 0 ] || rcctl reload httpd >/dev/null
	log "HTTPS is on for $domain"
}

# Root's scheduled jobs, between BEGIN and END marks so they can be
# replaced: the certificate daily, add-ons' hourly jobs, the System screen's
# requests every minute, and the nightly backup and update check. "~" picks a
# random minute, so servers don't all do it at the same moment.
cron_block() {
	cat <<EOF
# BEGIN BlowfishCMS
~ 3 * * * /usr/local/sbin/blowfishctl certificate >> /var/log/$NAME-acme.log 2>&1
~ * * * * su -s /bin/sh $(account admin) -c "/usr/bin/perl $APP/cgi-bin/site.pl --hourly" >> /var/log/$NAME-hourly.log 2>&1
* * * * * /usr/local/sbin/blowfishctl requests >> /var/log/$NAME-requests.log 2>&1
~ 3 * * * /usr/local/sbin/blowfishctl nightly >> /var/log/$NAME-backup.log 2>&1
# END BlowfishCMS
EOF
}
# Replaces the BlowfishCMS part of root's crontab, and adds the logs to
# newsyslog (log rotation) if they aren't there.
cron_install() {
	cur=$(mktemp /tmp/blowfish-cron.XXXXXXXXXX)
	crontab -u root -l 2>/dev/null | sed '/^# BEGIN BlowfishCMS$/,/^# END BlowfishCMS$/d' >"$cur" || true
	cron_block >>"$cur"
	crontab -u root "$cur"
	rm -f "$cur"
	for f in "/var/log/$NAME-acme.log" "/var/log/$NAME-hourly.log" "/var/log/$NAME-requests.log" "/var/log/$NAME-backup.log"; do
		[ -f "$f" ] || { : >"$f"; chmod 0640 "$f"; }
		grep -q "^$f " /etc/newsyslog.conf || printf '%s\troot:wheel\t640\t7\t512\t*\tZ\n' "$f" >>/etc/newsyslog.conf
	done
	f=$CONTACT/contact.log
	grep -q "^$f " /etc/newsyslog.conf || printf '%s\t%s:%s\t600\t10\t512\t*\tZ\n' "$f" "$(account contact)" "$(account public)" >>/etc/newsyslog.conf
}

# blowfishctl password [NAME]: htpasswd asks for the password (twice, not
# shown) and writes a bcrypt hash to a temporary file; only the hash is
# handed to site.pl --set-password, so the password itself never reaches the
# site's code or a command line.
set_password() {   # set_password [NAME]: an admin user's password; a new NAME becomes an owner
	user=${1:-$(conf_get admin_user)}
	case $user in [a-z_]*) ;; *) die "names start with a lowercase letter or _" ;; esac
	printf '%s' "$user" | grep -Eq '^[a-z_][a-z0-9_.-]{0,31}$' || die "names are up to 32 lowercase letters, numbers, dots, dashes or underscores"
	[ -t 0 ] || die "run this in a terminal (ssh -t ...): the password is typed, not passed"
	tmp=$(mktemp "$STORE/.htpasswd.XXXXXXXXXX")
	echo "Admin password for $user (at least 12 characters):" >&2
	htpasswd "$tmp" "$user" || { rm -f "$tmp"; die "password not changed"; }
	hash=$(sed -n "s/^$user://p" "$tmp")
	[ -n "$hash" ] || { rm -f "$tmp"; die "password not changed"; }
	rm -f "$tmp"
	printf '%s\n' "$hash" | as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --set-password '$user'" >&2 \
		|| die "the password could not be saved in the catalogue"
	log "admin password set for $user; their other sessions have ended"
}
# blowfishctl mail-token: asks for the Postmark token without showing it and
# stores it readable only by the contact account (written to a temporary file
# first, then moved into place).
set_mail_token() {
	[ -t 0 ] || die "run this in a terminal (ssh -t ...): the token is typed, not passed"
	printf 'Postmark server token (not shown): ' >&2
	stty -echo; read -r token; stty echo; echo >&2
	[ -n "$token" ] || die "no token given; nothing changed"
	tmp=$(mktemp "$SECRETS/.token.XXXXXXXXXX")
	printf '%s\n' "$token" >"$tmp"
	chown "$(account contact):$(account public)" "$tmp"; chmod 0400 "$tmp"; mv "$tmp" "$SECRETS/postmark.token"
	log "Postmark token saved; the contact form uses it from the next message"
}

# doas_setup: a new OpenBSD has doas but no /etc/doas.conf, so nobody can use
# it (and every blowfishctl command needs it). Writes the usual rule, letting
# the wheel group (the account made while installing OpenBSD, if it was put
# there) run commands as root, and checks it. An existing doas.conf is left
# as it is.
doas_setup() {
	if [ -f /etc/doas.conf ]; then return 0; fi
	log "doas: /etc/doas.conf allows the wheel group (permit persist :wheel)"
	echo "permit persist :wheel" >/etc/doas.conf.new
	chown root:wheel /etc/doas.conf.new; chmod 0600 /etc/doas.conf.new
	doas -C /etc/doas.conf.new || { rm -f /etc/doas.conf.new; die "doas: the new /etc/doas.conf didn't check"; }
	mv /etc/doas.conf.new /etc/doas.conf
	members=$(awk -F: '$1 == "wheel" {print $4}' /etc/group | tr , ' ')
	members=$(echo "$members" | sed 's/root//; s/^ *//; s/ *$//')
	if [ -n "$members" ]; then log "doas: usable by $members"; else log "doas: no one but root is in the wheel group; add your account with: usermod -G wheel NAME"; fi
}
# xbase_setup: p5-GD's image library needs freetype and fontconfig, which
# OpenBSD ships in the xbase set rather than as packages; many VPS images
# leave it out. Fetches this release's xbase and its signed checksums from
# cdn.openbsd.org, checks the signature with the release's own key
# (signify), and unpacks it.
xbase_setup() {
	if ls /usr/X11R6/lib/libfreetype.so.* >/dev/null 2>&1; then return 0; fi
	r=$(uname -r) m=$(machine); v=$(echo "$r" | tr -d .); base=https://cdn.openbsd.org/pub/OpenBSD/$r/$m
	log "xbase: this server has no xbase set (freetype and fontconfig, for pictures); fetching $base/xbase$v.tgz"
	work=$(mktemp -d /tmp/blowfish-xbase.XXXXXXXXXX)
	( cd "$work" && ftp -V "$base/xbase$v.tgz" "$base/SHA256.sig" >&2 && signify -Cp "/etc/signify/openbsd-$v-base.pub" -x SHA256.sig "xbase$v.tgz" >&2 ) || { rm -rf "$work"; die "xbase: couldn't fetch or check xbase$v.tgz from $base (see above); add the set by hand, then run install again"; }
	tar -xzphf "$work/xbase$v.tgz" -C / || { rm -rf "$work"; die "xbase: couldn't unpack xbase$v.tgz"; }
	rm -rf "$work"
	ldconfig -m /usr/X11R6/lib
	log "xbase: added and checked"
}

# ---- Commands --------------------------------------------------------------

# blowfishctl install: sets up a new site on a fresh server. Checks the
# options and the release, checks for the xbase set (GD needs its fonts
# libraries), installs the packages, makes the accounts, folders and settings
# file, puts the code in /opt/blowfishcms, builds the web root and the
# catalogue, the session key and the services, configures httpd over HTTP,
# gets a certificate and switches to HTTPS, then the System spool, the
# add-ons and themes lists, cron, and the admin password.
cmd_install() {
	domain='' aliases='' admin='' mail_from='' here=$(cd "$(dirname "$0")/.." && pwd)
	while [ $# -gt 0 ]; do
		case $1 in
		--domain) domain=${2:-}; shift 2 ;;
		--alias) aliases="$aliases ${2:-}"; shift 2 ;;
		--admin) admin=${2:-}; shift 2 ;;
		--mail-from) mail_from=${2:-}; shift 2 ;;
		*) die "install: unknown option $1" ;;
		esac
	done
	aliases=$(echo "$aliases" | sed 's/^ *//')
	echo "$domain" | grep -Eq '^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$' || die "install: --domain must be a host name such as example.org"
	for a in $aliases; do
		echo "$a" | grep -Eq '^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$' || die "install: --alias must be a host name such as www.example.org (got: $a)"
	done
	echo "$admin" | grep -Eq '^[a-z_][a-z0-9_.-]{0,31}$' || die "install: --admin must be a login name such as alice"
	[ -n "$mail_from" ] || mail_from="site@$domain"
	# A finished install has a release stamp; one that stopped part-way can be run again.
	[ ! -f "$APP/.release" ] || die "a site is already installed here ($CONF). Use blowfishctl update for new releases."
	check_files "$here"

	doas_setup
	xbase_setup
	log "installing packages: $PACKAGES"
	# shellcheck disable=SC2086
	pkg_add -I $PACKAGES >&2 || die "pkg_add failed"
	check_release "$here"
	log "accounts and folders"
	accounts
	folders
	log "settings: $CONF"
	cat >"$CONF.new" <<EOF
# BlowfishCMS site settings, written by blowfishctl install. Folders are as
# seen inside httpd's chroot ($CHROOT). Restart the services after a change:
#   blowfishctl restart
domain = $domain
aliases = $aliases
admin_user = $admin
data = ${DATA#"$CHROOT"}
media = ${MEDIA#"$CHROOT"}
comments = ${COMMENTS#"$CHROOT"}
contact = ${CONTACT#"$CHROOT"}
secrets = ${SECRETS#"$CHROOT"}
mail = postmark
mail_from = $mail_from
EOF
	chown root:wheel "$CONF.new"; chmod 0644 "$CONF.new"; mv "$CONF.new" "$CONF"

	log "code: $APP"
	if [ "$here" != "$APP" ]; then place_code "$here" "$APP"; fi
	date -u +%Y%m%dT%H%M%SZ >"$APP/.release"
	install_tool "$APP"
	build_web "$APP" "$WEB.new"; rm -rf "$WEB"; mv "$WEB.new" "$WEB"

	log "catalogue and comments"
	FRESH=1 migrate_with "$APP"
	chown "$(account admin):$(account public)" "$DB"; chmod 0640 "$DB"
	session_setup >/dev/null
	log "services"
	services_install
	restart_services || die "a service failed to start; see /var/log/daemon"

	log "httpd (HTTP first, so Let's Encrypt can check the domain)"
	httpd_apply plain
	if certificate; then
		https=1
	else
		https=0
		log "no certificate yet: check that $domain${aliases:+ and $aliases} point at this server, then run: blowfishctl certificate"
	fi
	system_dirs; catalog_lists_write; catalog_bundled "$APP"; cron_install

	if [ -t 0 ]; then set_password; else log "set the admin password with: blowfishctl password"; fi
	[ "$https" -eq 0 ] || smoke_test || log "warning: some addresses failed their check (above)"
	cat >&2 <<EOF

BlowfishCMS is installed.
  Site:   $( [ "$https" -eq 1 ] && echo "https://$domain/" || echo "http://$domain/   (HTTPS not yet: blowfishctl certificate)")
  Admin:  /admin/  (user $admin)
  Mail:   the contact form needs a Postmark token: blowfishctl mail-token
          (Postmark must allow sending from $mail_from)
  Status: blowfishctl status
EOF
}

# ---- Progress of an update, for the admin's System screen -----------------------
# When BLOWFISH_PROGRESS names a file (the request runner sets it), each step
# writes {step, steps, key, label, started, at, done:{KEY: seconds}} there.
# A finished update also leaves its step times in update-timings.json, so the
# next one can estimate how long it will take.
PROGRESS_N=0 PROGRESS_TOTAL=0 PROGRESS_KEY='' PROGRESS_AT=0 PROGRESS_START=0 PROGRESS_DONE=''
# progress KEY LABEL: records that the update has reached a new step, for
# the System screen's progress bar (only when BLOWFISH_PROGRESS names a
# file). It keeps how long each finished step took; the last step, "done",
# also saves those times for estimating the next update.
progress() {   # progress KEY LABEL: a new step starts (KEY is [a-z0-9:_-]; done ends)
	[ -n "${BLOWFISH_PROGRESS:-}" ] || return 0
	now=$(date +%s)
	[ "$PROGRESS_START" -gt 0 ] || PROGRESS_START=$now
	[ -z "$PROGRESS_KEY" ] || PROGRESS_DONE="$PROGRESS_DONE $PROGRESS_KEY=$((now - PROGRESS_AT))"
	PROGRESS_KEY=$1 PROGRESS_AT=$now
	[ "$1" = "done" ] || PROGRESS_N=$((PROGRESS_N + 1))
	[ "$PROGRESS_N" -le "$PROGRESS_TOTAL" ] || PROGRESS_TOTAL=$PROGRESS_N
	perl -MJSON::PP -e '
		my ($n,$total,$key,$label,$start,$at,$done)=@ARGV;
		my %done=map {split /=/,$_,2} grep {/\A[a-z0-9:_-]+=\d+\z/} split / /,$done;
		print JSON::PP->new->canonical->encode({step=>0+$n,steps=>0+$total,key=>$key,label=>$label,started=>0+$start,at=>0+$at,done=>{map {$_=>0+$done{$_}} keys %done}}),"\n";
	' "$PROGRESS_N" "$PROGRESS_TOTAL" "$1" "$2" "$PROGRESS_START" "$now" "$PROGRESS_DONE" >"$BLOWFISH_PROGRESS.tmp" || return 0
	root_file "$BLOWFISH_PROGRESS.tmp"; mv "$BLOWFISH_PROGRESS.tmp" "$BLOWFISH_PROGRESS"
	if [ "$1" = "done" ]; then
		cp "$BLOWFISH_PROGRESS" "$SYS/results/update-timings.json.tmp" && root_file "$SYS/results/update-timings.json.tmp" \
			&& mv "$SYS/results/update-timings.json.tmp" "$SYS/results/update-timings.json"
	fi
}
# The version number of a release's code (its $VERSION), or "unknown".
# A release's version number, read from its lib/BlowfishCMS.pm.
release_version() {   # release_version CODE-DIR
	v=$(sed -n "s/^our \$VERSION='\([0-9][0-9.]*\)'.*/\1/p" "$1/lib/BlowfishCMS.pm" 2>/dev/null | head -1)
	echo "${v:-unknown}"
}
# blowfishctl update [--check] [--skip-tests] RELEASE.tar.gz|latest. Step by
# step:
#   1. unpack the release into a temporary folder and check it compiles;
#   2. run the test suites it lists in tests/update-suites, each on a site of
#      its own, and upgrade.py on a copy of this site's catalogue; any failure
#      stops here with nothing changed (--check always stops here);
#   3. snapshot the catalogue into the kept releases;
#   4. copy the new code in next to the old (.incoming) and build its web root;
#   5. migrate the catalogue with the new code;
#   6. swap: the old code and web root move into the kept release, the new
#      ones into place;
#   7. restart the services and run the smoke test; if either fails, the old
#      code and web root are put back and the services restarted;
#   8. run the NEW release's own `blowfishctl httpd`, so new addresses work;
#   9. keep the newest $KEEP releases.
# The trap removes the temporary folders however it ends.
cmd_update() {
	mode=update tests=1 release=''
	while [ $# -gt 0 ]; do
		case $1 in
		--check) mode=check; shift ;;
		--skip-tests) tests=0; shift ;;
		-*) die "update: unknown option $1" ;;
		*) release=$1; shift ;;
		esac
	done
	[ -f "$CONF" ] || die "no site installed ($CONF missing); use blowfishctl install"
	if [ "$release" = latest ]; then
		releases_fetch
		v=$(release_latest_version) || die "no release found"
		[ "$v" != "$(release_version "$APP")" ] || { log "$v is already live"; return 0; }
		fetched=$(mktemp -d /var/tmp/blowfish-release.XXXXXXXXXX)
		release_download "$v" "$fetched" || { rm -rf "$fetched"; die "release $v couldn't be fetched"; }
		release=$fetched/blowfishcms.tar.gz
	fi
	[ -f "$release" ] || die "update: give the release file (a .tar.gz), or latest"
	stamp=$(date -u +%Y%m%dT%H%M%SZ)
	stage=$(mktemp -d /var/tmp/blowfish-update.XXXXXXXXXX)
	trap 'rm -rf "$stage" "$APP.incoming" "$WEB.incoming"' EXIT
	mkdir "$stage/src"
	tar -xzf "$release" -C "$stage/src"
	src=$stage/src
	# Accept one wrapping folder.
	# shellcheck disable=SC2012
	if [ ! -e "$src/cgi-bin" ] && [ "$(ls -A "$src" | wc -l)" -eq 1 ]; then src=$src/$(ls -A "$src"); fi
	PROGRESS_TOTAL=7   # check, snapshot, migrate, switch, restart, smoke, httpd (plus the test suites)
	progress check "Checking the release"
	log "checking the release"
	place_code "$src" "$stage/app"
	check_release "$stage/app"
	echo "$stamp" >"$stage/app/.release"
	# Sites installed before python3 was in install's packages get it now, so
	# the release's test suites can run before switching over.
	if [ "$tests" -eq 1 ] && ! command -v python3 >/dev/null 2>&1; then
		log "adding python3 (to run the release's tests)"
		pkg_add -I python%3 >&2 || log "python3 couldn't be added; the tests are skipped"
	fi
	if [ "$tests" -eq 1 ] && command -v python3 >/dev/null 2>&1; then
		# The release says which suites to run (tests/update-suites). Only
		# upgrade.py sees a copy of this site's catalogue; the others test the
		# code on catalogues of their own, so a site's pages and content can't
		# make an update fail.
		suites=$(sed -e 's/#.*//' "$stage/app/tests/update-suites" 2>/dev/null | tr -s ' \t\n' ' ')
		[ -n "$suites" ] || die "the release has no tests/update-suites; nothing was changed"
		run=''
		for t in $suites; do
			printf '%s' "$t" | grep -Eq '^[a-z0-9_-]+$' || continue
			[ -f "$stage/app/tests/$t.py" ] && run="$run $t"
		done
		n=$(echo "$run" | wc -w | tr -d ' ') k=0
		if [ "$mode" = update ]; then PROGRESS_TOTAL=$((n + 7)); else PROGRESS_TOTAL=$((n + 1)); fi
		for t in $run; do
			k=$((k + 1))
			if [ "$t" = upgrade ]; then progress "test:$t" "Testing this site's own data on a copy ($k of $n test suites)"
			else progress "test:$t" "Running the $t tests ($k of $n test suites)"; fi
			if [ "$t" = upgrade ]; then
				log "running tests/upgrade.py (this site's data, on a migrated copy; nothing live is touched)"
				(cd "$stage/app" && BLOWFISH_TEST_CATALOG=$DB python3 tests/upgrade.py tests/fcgi-cgi.pl) >"$stage/$t.log" 2>&1
			else
				log "running tests/$t.py"
				(cd "$stage/app" && python3 "tests/$t.py" tests/fcgi-cgi.pl) >"$stage/$t.log" 2>&1
			fi || { tail -20 "$stage/$t.log" >&2; die "tests/$t.py failed; nothing was changed"; }
			log "  $(tail -1 "$stage/$t.log")"
		done
	elif [ "$tests" -eq 1 ]; then
		log "python3 is not installed: tests skipped (pkg_add python3 to run them)"
	fi
	[ "$mode" = update ] || { progress "done" "All checks passed; nothing was changed"; log "all checks passed; nothing was changed (--check)"; return 0; }

	keep=$STORE/releases/$stamp
	install -d -o root -g wheel -m 0700 "$STORE/releases" "$keep"
	progress snapshot "Saving a snapshot of the catalogue"
	log "snapshotting the catalogue -> $keep/catalog.sqlite"
	snapshot_db "$DB" "$keep/catalog.sqlite"
	cp -Rp "$stage/app" "$APP.incoming"
	build_web "$APP.incoming" "$WEB.incoming"
	progress migrate "Updating the catalogue"
	log "updating the catalogue's tables"
	migrate_with "$APP.incoming" || { mv "$keep" "$STORE/releases/failed-$stamp"; die "migration failed; nothing was switched (snapshot kept in $STORE/releases/failed-$stamp)"; }
	progress switch "Switching to the new release"
	log "switching to release $stamp"
	mv "$APP" "$keep/app"; mv "$APP.incoming" "$APP"
	mv "$WEB" "$keep/web"; mv "$WEB.incoming" "$WEB"
	install_tool "$APP"
	up=1
	progress restart "Restarting the services"
	restart_services || up=0
	if [ "$up" -eq 1 ]; then progress smoke "Checking the site"; smoke_test || up=0; fi
	if [ "$up" -eq 0 ]; then
		progress rollback "Something failed: putting the previous code back"
		log "something failed: putting the previous code back"
		rm -rf "$APP" "$WEB"
		mv "$keep/app" "$APP"; mv "$keep/web" "$WEB"
		install_tool "$APP"
		restart_services || true
		mv "$keep" "$STORE/releases/failed-$stamp"
		die "update rolled back (the catalogue snapshot is in $STORE/releases/failed-$stamp)"
	fi
	rm -rf "$keep/web"
	# The new release's own blowfishctl writes httpd's configuration, so new
	# addresses (an admin screen, an add-on) work straight away.
	progress httpd "Updating httpd's configuration and scheduled jobs"
	sh "$APP/bin/blowfishctl" httpd || log "httpd's configuration wasn't updated; run: blowfishctl httpd"
	# (Release folders are named by UTC time stamps.)
	# shellcheck disable=SC2010
	ls -1t "$STORE/releases" | grep -Ev '^(failed|rolled-back)-' | sed -n "$((KEEP + 1)),\$p" | while read -r old; do rm -rf "${STORE:?}/releases/$old"; done
	progress "done" "Done: release $(release_version "$APP") is live"
	log "release $(release_version "$APP") ($stamp) is live. Undo with: blowfishctl rollback"
}

# blowfishctl rollback: puts back the code from before the last update. The
# current code is kept as rolled-back-TIME. The catalogue isn't changed (the
# older code works with the newer tables); its snapshot stays in case.
cmd_rollback() {
	prev=''
	# shellcheck disable=SC2045
	for entry in $(ls -1t "$STORE/releases" 2>/dev/null); do
		case $entry in failed-*|rolled-back-*) continue ;; esac
		[ -d "$STORE/releases/$entry/app" ] && { prev=$entry; break; }
	done
	[ -n "$prev" ] || die "no earlier release kept in $STORE/releases"
	log "putting back the code from before release $prev"
	cp -Rp "$STORE/releases/$prev/app" "$APP.incoming"
	build_web "$APP.incoming" "$WEB.incoming"
	out=$STORE/releases/rolled-back-$(date -u +%Y%m%dT%H%M%SZ)
	install -d -m 0700 "$out"
	mv "$APP" "$out/app"; mv "$APP.incoming" "$APP"
	rm -rf "$WEB"; mv "$WEB.incoming" "$WEB"
	install_tool "$APP"
	rm -rf "${STORE:?}/releases/${prev:?}/app"
	restart_services || log "a service failed to restart: see blowfishctl status"
	# The restored release's own blowfishctl writes httpd's configuration back,
	# so any addresses the newer release moved work again.
	sh "$APP/bin/blowfishctl" httpd || log "httpd's configuration wasn't updated; run: blowfishctl httpd"
	log "done. The catalogue was left as it is; its snapshot from before $prev is $STORE/releases/$prev/catalog.sqlite"
}

# blowfishctl status: the site, its release, whether each service runs, the
# certificate's expiry, free disk, memory and swap, uptime and crash dumps,
# the mail token, users and sign-in.
cmd_status() {
	echo "site:      $(site_url)/   (settings: $CONF)"
	echo "release:   $(release_version "$APP") (installed $(cat "$APP/.release" 2>/dev/null || echo "at an unknown time"))"
	for svc in $(for s in $(all_services); do service "$s"; done) httpd; do
		printf '%-18s %s\n' "$svc:" "$(rcctl check "$svc" >/dev/null 2>&1 && echo running || echo 'NOT RUNNING (rcctl start '"$svc"')')"
	done
	cert=/etc/ssl/$(conf_get domain).fullchain.pem
	if [ -f "$cert" ]; then
		echo "cert:      expires $(openssl x509 -enddate -noout -in "$cert" | cut -d= -f2)"
	else
		echo "cert:      none yet (blowfishctl certificate)"
	fi
	echo "disk:      $(df -h "$MEDIA" | awk 'NR==2 {print $4 " free of " $2 " on " $6}')"
	# Memory and swap as top sees them, how long since the server started,
	# and any crash dump the kernel left (savecore keeps them in /var/crash):
	# what to look at when the server has had to be switched off and on.
	echo "memory:    $(top -b -d 1 2>/dev/null | sed -n 's/^Memory: //p' | head -1)"
	echo "up:        $(uptime 2>/dev/null | sed 's/^.* up *//; s/, *[0-9]* users*.*//')"
	# shellcheck disable=SC2012
	echo "crashes:   $(ls -t /var/crash/bsd.*.core 2>/dev/null | head -3 | tr '\n' ' ' | sed 's/^$/none saved in \/var\/crash/')"
	echo "token:     $( [ -s "$SECRETS/postmark.token" ] && echo set || echo 'not set (blowfishctl mail-token)')"
	users=$(as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --users-count" 2>/dev/null || echo 0)
	echo "users:     $( [ "${users:-0}" -gt 0 ] 2>/dev/null && echo "$users admin user(s)" || echo 'none yet (blowfishctl password)')"
	echo "sign-in:   $( [ -s "$SESSION/session.key" ] && echo 'login page, with lockout' || echo "not set up (run: blowfishctl httpd)")"
}

# ---- What a site can install: its lists of add-ons and themes ------------------
# Each kind has a list, a folder of folders in $STORE (addons-catalog,
# themes-catalog). Archives join it: one the owner uploads on the Add-ons
# screen or the Themes tab (blowfishctl addon|theme add FILE), and the archive
# at the address in /etc/blowfishcms-addons-url (-themes-url) when the server
# has one, fetched by `refresh` and each night (there's no address unless one
# is set), and the release's own catalog/addons and catalog/themes, which the
# add-ons and themes repositories are bundled into (catalog_bundled). An archive holds one add-on (theme) or several: NAME/addon.json,
# TOP/NAME/addon.json (a repository's archive) or addon.json alone. One older
# than the list's copy of it is left out. The list is written to
# $SYS/results/addons.json (themes.json) for the admin; installing copies an
# add-on from it into $ADDONS_EXTRA/NAME, keeping the replaced copy as
# .NAME.previous.TIME (the newest three).
CATALOG=$STORE/addons-catalog
THEMES_CATALOG=$STORE/themes-catalog
# Sets the variables for working on add-ons or on themes, so the list code
# below serves both.
catalog_kind() {   # catalog_kind addon|theme: sets CAT, MANIFEST, NAME_RE, LISTS and LABEL
	case $1 in
	addon) CAT=$CATALOG MANIFEST=addon.json NAME_RE='^[a-z][a-z0-9]{1,19}$' LISTS=addons LABEL=add-ons ;;
	theme) CAT=$THEMES_CATALOG MANIFEST=theme.json NAME_RE='^[a-z][a-z0-9-]{1,31}$' LISTS=themes LABEL=themes ;;
	*) die "there's no kind called $1" ;;
	esac
}
# One plain value from an addon.json or theme.json (Perl reads the JSON).
manifest_field() {   # manifest_field FILE KEY: a plain value from an addon.json or theme.json
	perl -MJSON::PP -e 'local $/; open my $f, "<", $ARGV[0] or exit 1; my $m = eval {JSON::PP->new->decode(<$f>)}; my $v = ref $m eq "HASH" ? $m->{$ARGV[1]} : undef; print defined $v && !ref $v ? $v : ""' "$1" "$2"
}
# True (exit 0) when version A is older than B, comparing number by number.
version_older() {   # version_older A B: true when version A is older than B
	perl -e 'my @a = split /\./, $ARGV[0]; my @b = split /\./, $ARGV[1]; for (0 .. 3) {my $c = (($a[$_] // 0) + 0) <=> (($b[$_] // 0) + 0); exit($c < 0 ? 0 : 1) if $c} exit 1' "$1" "$2"
}
# Puts the add-ons (themes) in an archive or folder into the site's list:
# unpacks it into a temporary folder (refusing more than 32 MB, links and
# special files), finds each manifest (at the top, one level or two levels
# down), and copies each valid one in, unless the list already has a newer
# version. Then writes the list for the admin.
catalog_add() {   # catalog_add KIND ARCHIVE|FOLDER: puts the add-ons (themes) in it in the list
	catalog_kind "$1"
	cw=$(mktemp -d /var/tmp/blowfish-catalog.XXXXXXXXXX)
	if [ -d "$2" ]; then cp -R "$2/." "$cw/"
	else
		[ "$(wc -c <"$2")" -le 33554432 ] || { rm -rf "$cw"; die "the archive is larger than 32 MB"; }
		tar -xzf "$2" -C "$cw" 2>/dev/null || { rm -rf "$cw"; die "that isn't a .tar.gz archive"; }
	fi
	if find "$cw" ! -type f ! -type d | grep -q .; then rm -rf "$cw"; die "the archive holds links or other special files"; fi
	install -d -o root -g wheel -m 0755 "$CAT"
	found=0 added=''
	for m in "$cw/$MANIFEST" "$cw"/*/"$MANIFEST" "$cw"/*/*/"$MANIFEST"; do
		[ -f "$m" ] || continue
		found=$((found + 1)); dir=$(dirname "$m")
		n=$(manifest_field "$m" name); v=$(manifest_field "$m" version)
		if ! echo "$n" | grep -Eq "$NAME_RE"; then log "left out ${dir#"$cw"/}: its $MANIFEST has no valid name"; continue; fi
		if [ "$dir" != "$cw" ] && [ "$(basename "$dir")" != "$n" ]; then log "left out ${dir#"$cw"/}: the folder of $n must be called $n"; continue; fi
		have=''; [ ! -f "$CAT/$n/$MANIFEST" ] || have=$(manifest_field "$CAT/$n/$MANIFEST" version)
		if [ -n "$have" ] && version_older "$v" "$have"; then log "left out $n $v: the list has $have"; continue; fi
		rm -rf "$CAT/.$n.new"; cp -R "$dir" "$CAT/.$n.new"
		chown -R root:wheel "$CAT/.$n.new"; chmod -R u=rwX,go=rX "$CAT/.$n.new"
		rm -rf "${CAT:?}/$n"; mv "$CAT/.$n.new" "$CAT/$n"
		[ "$have" = "$v" ] || added="$added, $n $v"
	done
	rm -rf "$cw"
	[ "$found" -gt 0 ] || die "there's no $MANIFEST in the archive"
	catalog_list_write
	total=$(find "$CAT" -mindepth 2 -maxdepth 2 -name "$MANIFEST" | wc -l | tr -d ' ')
	if [ -n "$added" ]; then log "the $LABEL list has ${added#, } added: $total in all"; else log "the $LABEL list has nothing new: $total in all"; fi
}
# Adds the archive from the server's address (/etc/blowfishcms-addons-url or
# -themes-url), if it has one.
catalog_fetch() {   # catalog_fetch KIND [quiet]: adds the archive at the server's address, if it has one
	catalog_kind "$1"
	url=$(update_address "$LISTS")
	if [ -z "$url" ]; then
		[ "${2:-}" = quiet ] || die "this server has no address to fetch $LABEL from: set Updates from on the System screen (or: blowfishctl updates-from URL); or upload them in the admin, or: blowfishctl ${1} add FILE"
		catalog_list_write; return 0
	fi
	fw=$(mktemp -d /var/tmp/blowfish-fetch.XXXXXXXXXX)
	log "fetching the $LABEL from $url"
	if ! ftp -V -w 30 -o "$fw/list.tar.gz" "$url" >/dev/null; then rm -rf "$fw"; die "the $LABEL couldn't be fetched from $url"; fi
	rc=0; (catalog_add "$1" "$fw/list.tar.gz") || rc=$?
	rm -rf "$fw"; [ "$rc" -eq 0 ] || return "$rc"
	touch "$CAT/.fetched"; catalog_list_write
}
# What the admin shows: the list, and the address (empty when there's none).
catalog_list_write() {   # after catalog_kind
	[ -d "$SYS/results" ] || return 0
	perl -MJSON::PP -e '
		my ($kind,$dir,$url)=@ARGV; my $file=$kind eq "addon" ? "addon.json" : "theme.json";
		my $ok=$kind eq "addon" ? qr/\A[a-z][a-z0-9]{1,19}\z/ : qr/\A[a-z][a-z0-9-]{1,31}\z/; my @list;
		for my $f (sort glob "$dir/*/$file") {
			my ($folder)=$f =~ m{/([^/]+)/\Q$file\E\z} or next;
			open my $fh,"<:raw",$f or next; local $/; my $m=eval {JSON::PP->new->utf8->decode(<$fh>)};
			next unless ref $m eq "HASH" && ($m->{name}//"") eq $folder && $folder =~ $ok;
			my %e=map {defined $m->{$_} ? ($_=>$m->{$_}) : ()} qw(name label version blowfishcms description author), $kind eq "addon" ? qw(service network) : ();
			$e{variants}=[map {+{slug=>$_->{slug},name=>$_->{name},scheme=>$_->{scheme}}} grep {ref $_ eq "HASH"} @{ref $m->{variants} eq "ARRAY" ? $m->{variants} : []}] if $kind eq "theme";
			push @list,\%e;
		}
		my $fetched=(stat "$dir/.fetched")[9];
		print JSON::PP->new->utf8->canonical->encode({source=>$url,($fetched ? (fetched=>$fetched) : ()),($kind eq "addon" ? "addons" : "themes")=>\@list}),"\n";
	' "$( [ "$LISTS" = addons ] && echo addon || echo theme)" "$CAT" "$(update_address "$LISTS")" >"$SYS/results/$LISTS.json.tmp"
	root_file "$SYS/results/$LISTS.json.tmp"; mv "$SYS/results/$LISTS.json.tmp" "$SYS/results/$LISTS.json"
}
catalog_lists_write() { catalog_kind addon; catalog_list_write; catalog_kind theme; catalog_list_write; }
# The add-ons and themes bundled with the release (catalog/addons, catalog/themes)
# join the lists; the first time this release does it, every installed one with
# a newer version is updated to it, so one release upload updates them all.
# Nothing new is installed. Runs from install and the httpd step (so the new
# release's script, at the end of an update).
# The add-ons and themes bundled in the release (catalog/) join the lists; the
# first time a release does this, every installed one with a newer bundled
# version is updated. catalog-bundled.version remembers which release did it.
catalog_bundled() {   # catalog_bundled CODE-DIR
	for kind in addon theme; do
		catalog_kind "$kind"
		[ ! -d "$1/catalog/$LISTS" ] || (catalog_add "$kind" "$1/catalog/$LISTS") || log "the $LABEL bundled with this release couldn't be added to the list"
	done
	v=$(release_version "$1")
	[ "$(cat "$STORE/catalog-bundled.version" 2>/dev/null)" != "$v" ] || return 0
	if [ -d "$1/catalog" ] && [ -d "$SYS/results" ]; then
		log "updating the add-ons and themes this site has to the versions bundled with $v"
		(PINS='' update_all addon theme) || log "not every add-on and theme was updated: see above; the rest keep the version they had"
	fi
	echo "$v" >"$STORE/catalog-bundled.version"
}
# What site.pl says about an installed add-on: "ok" or its problem.
addon_status() {   # addon_status NAME: "ok", a problem, or nothing when it isn't found
	as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --addons" 2>/dev/null | awk -F '\t' -v n="$1" '$1 == n {print $4}'
}
# Installs or updates an add-on from the list: copies it in as NAME.new,
# moves the current one aside as .NAME.previous.TIME, and puts the new one in
# place; if the site says it can't be used, the previous one is put back.
# Keeps the three newest previous copies, rebuilds the web root, and if the
# add-on is on, migrates and restarts the services.
addon_put() {   # addon_put DIR install|update
	n=$(manifest_field "$1/addon.json" name) || die "addon.json can't be read"
	echo "$n" | grep -Eq '^[a-z][a-z0-9]{1,19}$' || die "addon.json has no valid name"
	if find "$1" -type l | grep -q .; then die "the add-on contains symlinks"; fi
	install -d -o root -g wheel -m 0755 "$ADDONS_EXTRA"
	rm -rf "$ADDONS_EXTRA/$n.new"; cp -R "$1" "$ADDONS_EXTRA/$n.new"
	chown -R root:wheel "$ADDONS_EXTRA/$n.new"; chmod -R u=rwX,go=rX "$ADDONS_EXTRA/$n.new"
	prev=''
	if [ -d "$ADDONS_EXTRA/$n" ]; then prev=$ADDONS_EXTRA/.$n.previous.$(date -u +%Y%m%dT%H%M%SZ); mv "$ADDONS_EXTRA/$n" "$prev"; fi
	mv "$ADDONS_EXTRA/$n.new" "$ADDONS_EXTRA/$n"
	# It must suit this release (its addon.json is checked as the site reads it).
	st=$(addon_status "$n")
	if [ "$st" != ok ]; then
		rm -rf "${ADDONS_EXTRA:?}/${n:?}"
		[ -z "$prev" ] || mv "$prev" "$ADDONS_EXTRA/$n"
		die "$n can't be used here: ${st:-its addon.json is unreadable}${prev:+ (the installed version is kept)}"
	fi
	# shellcheck disable=SC2012  # names this script made
	ls -1dt "$ADDONS_EXTRA/.$n.previous."* 2>/dev/null | tail -n +4 | while IFS= read -r old; do rm -rf "$old"; done
	build_web "$APP" "$WEB.new"; rm -rf "$WEB"; mv "$WEB.new" "$WEB"
	v=$(manifest_field "$ADDONS_EXTRA/$n/addon.json" version)
	if addons_on | grep -q "^$n "; then
		# A version that runs its own service (when the one before didn't)
		# needs what switching it on makes: its account, private folders,
		# service and httpd addresses. Switching it on again does all that,
		# and changes nothing that's already in place.
		if addons_on | grep -q "^$n service "; then sh "$0" addon enable "$n"; fi
		as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --migrate" >&2
		restart_services || true
		log "$n $v is in place and running"
	else
		log "$n $v is installed. Switch it on with: blowfishctl addon enable $n"
	fi
}
# blowfishctl addon SUBCOMMAND: list, enable, disable, refresh, add,
# install, update (or update --all) and remove. Enabling one with its own
# service makes its account and private folders first, then its service and
# httpd addresses; disabling stops its service. Removing keeps its folder as
# .NAME.removed.TIME and its data.
cmd_addon() {
	sub=${1:-list}; [ $# -gt 0 ] && shift
	case $sub in
	list)
		as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --addons" | awk -F '\t' 'BEGIN {printf "%-20s %-4s %-8s %s\n", "ADD-ON", "ON", "SERVICE", "STATUS"} {printf "%-20s %-4s %-8s %s\n", $1, $2, $3, $4}'
		;;
	enable|disable)
		n=${1:-}
		echo "$n" | grep -Eq '^[a-z][a-z0-9]{1,19}$' || die "addon $sub: give the add-on's name (see blowfishctl addon list)"
		line=$(as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --addons" | awk -F '\t' -v n="$n" '$1 == n')
		[ -n "$line" ] || die "there's no add-on called $n (see blowfishctl addon list)"
		kind=$(echo "$line" | cut -f3) problem=$(echo "$line" | cut -f4)
		[ "$problem" = ok ] || die "$n can't be used: $problem"
		if [ "$sub" = enable ]; then
			if [ "$kind" = service ]; then
				ensure_account "$(account "x$n")" "$(account public)"
				install -d -o root -g wheel -m 0755 "$ADDON_DATA" "$ADDON_SECRETS"
				install -d -o "$(account "x$n")" -g "$(account public)" -m 0700 "$ADDON_DATA/$n" "$ADDON_SECRETS/$n"
			fi
			as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --addon-enable $n" >&2 || die "$n could not be switched on (see above)"
			addon_files_dirs
			if [ "$kind" = service ]; then
				services_install "x$n"
				rcctl restart "$(service "x$n")" >/dev/null || die "the $(service "x$n") service failed to start; see /var/log/daemon"
			fi
			httpd_apply "$(httpd_mode)"
			log "$n is on"
		else
			as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --addon-disable $n" >&2
			httpd_apply "$(httpd_mode)"
			if [ "$kind" = service ]; then
				rcctl stop "$(service "x$n")" >/dev/null 2>&1 || true
				rcctl disable "$(service "x$n")" >/dev/null 2>&1 || true
			fi
			log "$n is off; its data is kept in $ADDON_DATA/$n"
		fi
		;;
	refresh) catalog_fetch addon ;;
	add)
		[ -f "${1:-}" ] || die "addon add: give a .tar.gz of an add-on's folder, or of several"
		log "adding $1 to the add-ons list: only install add-ons from a source you trust"
		catalog_add addon "$1" ;;
	install|update)
		arg=${1:-}
		if [ "$sub" = update ] && [ "$arg" = --all ]; then
			PINS='' update_all addon
		else
			echo "$arg" | grep -Eq '^[a-z][a-z0-9]{1,19}$' || die "addon $sub: give the add-on's name (blowfishctl addon add FILE puts one in the list)"
			if [ "$sub" = update ]; then [ -d "$ADDONS_EXTRA/$arg" ] || die "$arg isn't installed"; fi
			if [ "$sub" = install ] && [ -d "$ADDONS_EXTRA/$arg" ]; then die "$arg is already installed; use: blowfishctl addon update $arg"; fi
			(catalog_fetch addon quiet) || log "the add-ons couldn't be fetched; using the list as it is"
			[ -f "$CATALOG/$arg/addon.json" ] || die "there's no add-on called $arg in the list (upload it on the Add-ons screen, or: blowfishctl addon add FILE)"
			addon_put "$CATALOG/$arg" "$sub"
		fi
		;;
	remove)
		n=${1:-}
		echo "$n" | grep -Eq '^[a-z][a-z0-9]{1,19}$' || die "addon remove: give the add-on's name"
		[ -d "$ADDONS_EXTRA/$n" ] || die "$n isn't an installed add-on"
		if addons_on | grep -q "^$n "; then die "switch $n off first: blowfishctl addon disable $n"; fi
		mv "$ADDONS_EXTRA/$n" "$ADDONS_EXTRA/.$n.removed.$(date -u +%Y%m%dT%H%M%SZ)"
		build_web "$APP" "$WEB.new"; rm -rf "$WEB"; mv "$WEB.new" "$WEB"
		log "$n removed (kept in $ADDONS_EXTRA/.$n.removed.*; its data stays in $ADDON_DATA/$n)"
		;;
	*) die "addon: use list, add, refresh, install, update, enable, disable or remove" ;;
	esac
}
# ---- Where updates come from ------------------------------------------------------
# One address, a Repositories add-on's (https://example.org/x/repos/), set on
# the System screen or with blowfishctl updates-from and kept in
# /etc/blowfishcms-updates-from. From it: the newest release is
# ADDRESS/blowfishcms/releases/latest (in the GitHub API's form, which
# Repositories answers), the add-ons ADDRESS/blowfishcms-addons/archive/
# latest.tar.gz and the themes ADDRESS/blowfishcms-themes/archive/
# latest.tar.gz. /etc/blowfishcms-releases-url, -addons-url and -themes-url
# still name one of them outright. Without any, nothing is looked for.
address_ok() { printf '%s' "$1" | grep -Eq '^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[A-Za-z0-9._~-]+)*/?$'; }
updates_from() { a=$(head -1 "/etc/$NAME-updates-from" 2>/dev/null || true); if address_ok "$a"; then echo "${a%/}/"; fi; }
update_address() {   # update_address releases|addons|themes: where to fetch it, or nothing
	u=$(head -1 "/etc/$NAME-$1-url" 2>/dev/null || true)
	if [ -z "$u" ] && [ -n "$(updates_from)" ]; then
		case $1 in releases) u="$(updates_from)$NAME/releases/latest" ;; *) u="$(updates_from)$NAME-$1/archive/latest.tar.gz" ;; esac
	fi
	echo "$u"
}
# blowfishctl updates-from [URL | none]: shows, sets or clears the address.
cmd_updates_from() {
	case ${1:-} in
	'') a=$(updates_from); echo "${a:-not set}" ;;
	none) rm -f "/etc/$NAME-updates-from"; log "updates aren't looked for (set an address with: blowfishctl updates-from https://example.org/x/repos/)" ;;
	*)
		address_ok "$1" || die "updates-from: give a Repositories add-on's address, such as https://example.org/x/repos/"
		printf '%s\n' "${1%/}/" >"/etc/$NAME-updates-from"; chmod 0644 "/etc/$NAME-updates-from"
		log "updates come from ${1%/}/" ;;
	esac
	# The System, Add-ons and Themes screens show where things come from.
	if [ -d "$SYS/results" ]; then system_state; catalog_lists_write; fi
}
# ---- New releases ---------------------------------------------------------------
# The newest release's version, notes and the addresses of its archive and
# .sha256 go in $SYS/results/releases.json for the System screen and the
# notifications. Each release is published with blowfishcms.tar.gz and
# blowfishcms.tar.gz.sha256.
# Looks up the newest release (update_address) and writes its version,
# archive and sha256 addresses and notes to releases.json for the System
# screen and the notifications. A reply that isn't a usable release is refused.
releases_fetch() {
	url=$(update_address releases)
	[ -n "$url" ] || die "there's no address to look for new releases at: set Updates from on the System screen, or: blowfishctl updates-from https://example.org/x/repos/"
	fw=$(mktemp -d /var/tmp/blowfish-releases.XXXXXXXXXX)
	log "checking for a new release at $url"
	if ! ftp -V -w 30 -o "$fw/latest.json" "$url" >/dev/null; then rm -rf "$fw"; die "the releases couldn't be fetched from $url"; fi
	if ! perl -MJSON::PP -e '
		my ($file,$url)=@ARGV; local $/; open my $fh,"<:raw",$file or die "unreadable\n";
		my $r=eval {JSON::PP->new->utf8->decode(<$fh>)}; die "not JSON\n" unless ref $r eq "HASH";
		my ($v)=($r->{tag_name}//"") =~ /\Av?(\d+\.\d+\.\d+)\z/ or die "the newest release has no version tag\n";
		my %a=map {($_->{name}//"")=>($_->{browser_download_url}//"")} grep {ref $_ eq "HASH"} @{ref $r->{assets} eq "ARRAY" ? $r->{assets} : []};
		for ("blowfishcms.tar.gz","blowfishcms.tar.gz.sha256") {die "release $v has no $_\n" unless $a{$_} =~ m{\A(?:https://|file:/)[^\s"]+\z}}
		my $notes=substr($r->{body}//"",0,4000);
		print JSON::PP->new->utf8->canonical->encode({fetched=>time,source=>$url,latest=>{version=>$v,archive=>$a{"blowfishcms.tar.gz"},sha256=>$a{"blowfishcms.tar.gz.sha256"},
			page=>(($r->{html_url}//"") =~ m{\Ahttps://} ? $r->{html_url} : ""),published=>$r->{published_at}//"",notes=>$notes}}),"\n";
	' "$fw/latest.json" "$url" >"$fw/releases.json"; then rm -rf "$fw"; die "what came from $url isn't a release this can use"; fi
	if [ -d "$SYS/results" ]; then root_file "$fw/releases.json"; mv "$fw/releases.json" "$SYS/results/releases.json"; else cp "$fw/releases.json" "$STORE/releases.json"; fi
	rm -rf "$fw"
	log "the newest release is $(release_latest_version)"
}
# The newest release's version from releases.json.
release_latest_version() {
	f=$SYS/results/releases.json; [ -f "$f" ] || f=$STORE/releases.json
	perl -MJSON::PP -e 'local $/; open my $fh,"<",$ARGV[0] or exit 1; my $r=eval {JSON::PP->new->decode(<$fh>)} or exit 1; my $v=$r->{latest}{version}//""; $v =~ /\A\d+\.\d+\.\d+\z/ or exit 1; print $v' "$f"
}
# release_download VERSION DIR: fetches that release and its published
# sha256, and refuses the archive unless they match. Only the newest
# release can be fetched this way.
release_download() {   # release_download VERSION DIR: DIR/blowfishcms.tar.gz, its sha256 checked
	f=$SYS/results/releases.json; [ -f "$f" ] || f=$STORE/releases.json
	[ "$(release_latest_version)" = "$1" ] || die "$1 isn't the newest release (check for updates again)"
	a=$(perl -MJSON::PP -e 'local $/; open my $fh,"<",$ARGV[0] or exit 1; my $r=JSON::PP->new->decode(<$fh>); print $r->{latest}{archive}' "$f")
	h=$(perl -MJSON::PP -e 'local $/; open my $fh,"<",$ARGV[0] or exit 1; my $r=JSON::PP->new->decode(<$fh>); print $r->{latest}{sha256}' "$f")
	log "fetching release $1 from $a"
	ftp -V -w 60 -o "$2/blowfishcms.tar.gz" "$a" >/dev/null || die "release $1 couldn't be fetched"
	ftp -V -w 30 -o "$2/blowfishcms.tar.gz.sha256" "$h" >/dev/null || die "the sha256 of release $1 couldn't be fetched"
	want=$(grep -Eo '[0-9a-f]{64}' "$2/blowfishcms.tar.gz.sha256" | head -1)
	got=$(sha256 -q "$2/blowfishcms.tar.gz")
	echo "$want" | grep -Eq '^[0-9a-f]{64}$' || die "the published sha256 of release $1 isn't readable"
	[ "$want" = "$got" ] || die "release $1 doesn't match its published sha256 (got $got, expected $want); nothing was changed"
	log "release $1 matches its published sha256 $got"
}
# The nightly check (and "check now"): the newest release, and the add-ons'
# and themes' lists, then an email to the alerts address about anything new.
check_updates() {
	(releases_fetch) || log "the releases couldn't be checked"
	(catalog_fetch addon quiet) || log "the add-ons couldn't be fetched"
	(catalog_fetch theme quiet) || log "the themes couldn't be fetched"
	(places_fetch) || log "the city database for Analytics couldn't be fetched (it's tried again tomorrow)"
	[ ! -d "$SYS/results" ] || system_state
	alerts_send
}
# ---- Analytics' places --------------------------------------------------------------
# DB-IP's IP to City Lite (CC BY 4.0) comes out monthly; it's fetched once a
# month (last month's until this month's is out) into the Analytics folder,
# which only the comments account can read, and checked by that account
# before it replaces the old one. The comments service reopens it by itself.
# Fetches Analytics' city database (this month's, or last month's while this
# month's isn't out), unpacks it, refuses one over 512 MB, has the comments
# account check it can read it, and only then replaces the old one.
# places.month records which month it is, so it's fetched once a month.
places_fetch() {
	dir=$COMMENTS/analytics
	[ -d "$dir" ] || return 0
	month=$(date +%Y-%m)
	if [ "${1:-}" != now ] && [ -f "$dir/places.mmdb" ] && [ "$(cat "$dir/places.month" 2>/dev/null)" = "$month" ]; then return 0; fi
	before=$(/usr/bin/perl -e '@t=localtime;$m=$t[4];$y=$t[5]+1900;if($m==0){$m=12;$y--}printf "%04d-%02d",$y,$m')
	url=$(head -1 "/etc/$NAME-places-url" 2>/dev/null || true)
	[ -n "$url" ] || url=$PLACES_URL
	pw=$(mktemp -d /var/tmp/blowfish-places.XXXXXXXXXX)
	got=''
	for m in "$month" "$before"; do
		u=$(printf '%s' "$url" | sed "s/MONTH/$m/g")
		if ftp -V -w 60 -o "$pw/places.gz" "$u" >/dev/null 2>&1 && gzip -dc "$pw/places.gz" >"$pw/places.mmdb" 2>/dev/null && [ -s "$pw/places.mmdb" ]; then got=$m; break; fi
		rm -f "$pw/places.gz" "$pw/places.mmdb"
	done
	if [ -z "$got" ]; then rm -rf "$pw"; die "the city database couldn't be fetched from $url (for $month or $before)"; fi
	if [ "$(wc -c <"$pw/places.mmdb")" -gt 536870912 ]; then rm -rf "$pw"; die "the city database is larger than 512 MB"; fi
	com=$(account comments)
	install -o "$com" -g "$(account public)" -m 0600 "$pw/places.mmdb" "$dir/places.mmdb.new"
	rm -rf "$pw"
	if ! as_user "$com" "/usr/bin/perl '$APP/cgi-bin/site.pl' --places-check '$dir/places.mmdb.new'" >&2; then
		rm -f "$dir/places.mmdb.new"; die "the city database from $u isn't one Analytics can read; the old one stays"
	fi
	mv "$dir/places.mmdb.new" "$dir/places.mmdb"
	if [ "$got" = "$month" ]; then printf '%s\n' "$got" >"$dir/places.month"; else rm -f "$dir/places.month"; fi
	log "Analytics' city database is DB-IP's for $got"
}
# Emails new update notices to the alerts address, in three steps as three
# accounts (see alert_mail_cli in Notices.pm). Exit 3 from the sender means
# there's no address or token yet: the notices wait.
alerts_send() {
	pending=$(as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --notices-pending" 2>/dev/null) || return 0
	[ -n "$pending" ] || return 0
	rc=0; printf '%s\n' "$pending" | as_user "$(account contact)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --alert-mail" >&2 || rc=$?
	case $rc in
	0) as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --notices-emailed" >/dev/null ;;
	3) ;;   # no alerts address or token yet: they wait
	*) log "the update alert couldn't be emailed (it's tried again tomorrow)" ;;
	esac
}
# ---- Themes --------------------------------------------------------------------
# From the themes list (above) into $THEMES_EXTRA/NAME, the replaced copy kept
# as .NAME.previous.TIME (the newest three). The site reads the folders as
# they are, so nothing needs restarting.
# What site.pl says about an installed theme: "ok" or its problem.
theme_status() {   # theme_status NAME: "ok", a problem, or nothing when it isn't found
	as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --themes" 2>/dev/null | awk -F '\t' -v n="$1" '$1 == n {print $4}'
}
# Installs or updates a theme from the list, the same way as addon_put
# (refusing to replace one that comes with the release).
theme_put() {   # theme_put DIR
	n=$(manifest_field "$1/theme.json" name) || die "no theme.json"
	echo "$n" | grep -Eq '^[a-z][a-z0-9-]{1,31}$' || die "theme.json has no valid name"
	[ ! -d "$APP/themes/$n" ] || die "$n comes with BlowfishCMS"
	install -d -o root -g wheel -m 0755 "$THEMES_EXTRA"
	rm -rf "$THEMES_EXTRA/$n.new"; cp -R "$1" "$THEMES_EXTRA/$n.new"
	chown -R root:wheel "$THEMES_EXTRA/$n.new"; chmod -R u=rwX,go=rX "$THEMES_EXTRA/$n.new"
	prev=
	if [ -d "$THEMES_EXTRA/$n" ]; then prev=$THEMES_EXTRA/.$n.previous.$(date -u +%Y%m%dT%H%M%SZ); mv "$THEMES_EXTRA/$n" "$prev"; fi
	mv "$THEMES_EXTRA/$n.new" "$THEMES_EXTRA/$n"
	st=$(theme_status "$n")
	if [ "$st" != ok ]; then
		rm -rf "${THEMES_EXTRA:?}/${n:?}"
		[ -z "$prev" ] || mv "$prev" "$THEMES_EXTRA/$n"
		die "$n can't be used here: ${st:-its theme.json is unreadable}${prev:+ (the installed version is kept)}"
	fi
	# shellcheck disable=SC2012  # names this script made
	ls -1dt "$THEMES_EXTRA/.$n.previous."* 2>/dev/null | tail -n +4 | while IFS= read -r old; do rm -rf "$old"; done
	build_web "$APP" "$WEB.new"; rm -rf "$WEB"; mv "$WEB.new" "$WEB"
	log "theme $n $(manifest_field "$THEMES_EXTRA/$n/theme.json" version) is in place; its variants appear on the Themes tab"
}
# ---- Updating every add-on and theme ----------------------------------------------------
# update_all addon [theme]: fetches the lists once (where there's an address), then updates
# each installed add-on (or theme) that has a newer version, one at a time. One
# that fails keeps the version it had and the rest carry on; ones that need a
# newer BlowfishCMS are skipped. With $PINS (from an update-all request: "TYPE
# NAME VERSION" lines), only those, and only at the version the owner was shown.
# The log says "updating N of M: NAME" as it goes and ends with "summary: …".
# update_all addon [theme]: see above.
update_all() {
	plan=$(mktemp /var/tmp/blowfish-updates.XXXXXXXXXX); skipped=''; updated=''; failed=''
	for kind in "$@"; do
		(catalog_fetch "$kind" quiet) || log "the ${kind}s couldn't be fetched; using the list as it is"
		as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --updates $kind" >"$plan.$kind" || { rm -f "$plan" "$plan".*; die "the $kind updates couldn't be listed"; }
		while IFS="$(printf '\t')" read -r n v needs; do
			echo "$n" | grep -Eq '^[a-z][a-z0-9-]{1,31}$' || continue
			if [ -n "${PINS:-}" ]; then
				want=$(printf '%s\n' "$PINS" | awk -v t="$kind" -v n="$n" '$1 == t && $2 == n {print $3}')
				[ -n "$want" ] || continue
				if [ "$want" != "$v" ]; then skipped="$skipped, $n (now $v, not the $want shown: check and update again)"; continue; fi
			fi
			if [ -n "$needs" ]; then skipped="$skipped, $n $v (needs BlowfishCMS $needs: update BlowfishCMS first)"; continue; fi
			printf '%s %s %s\n' "$kind" "$n" "$v" >>"$plan"
		done <"$plan.$kind"
		# Pinned ones with no update now: updated already, or removed since.
		if [ -n "${PINS:-}" ]; then
			for n in $(printf '%s\n' "$PINS" | awk -v t="$kind" '$1 == t {print $2}'); do
				awk -v n="$n" '$1 == n {f=1} END {exit !f}' "$plan.$kind" || skipped="$skipped, $n (no update now)"
			done
		fi
	done
	total=$(wc -l <"$plan" | tr -d ' '); i=0
	while read -r kind n v; do
		i=$((i + 1)); log "updating $i of $total: $n to $v"
		rc=0
		if [ "$kind" = addon ]; then (addon_put "$CATALOG/$n" update) || rc=$?; else (theme_put "$THEMES_CATALOG/$n") || rc=$?; fi
		if [ "$rc" -eq 0 ]; then updated="$updated, $n $v"; else failed="$failed, $n"; log "$n wasn't updated; it keeps the version it had"; fi
	done <"$plan"
	rm -f "$plan" "$plan".*
	[ -n "$updated" ] || updated=', nothing'
	log "summary: updated ${updated#, }${skipped:+; skipped ${skipped#, }}${failed:+; failed ${failed#, }}"
	[ -z "$failed" ]
}
# blowfishctl theme SUBCOMMAND: list, refresh, add, install, update (or
# update --all) and remove (which first deletes its variants from the
# catalogue, so none is left pointing at missing files).
cmd_theme() {
	sub=${1:-list}; [ $# -eq 0 ] || shift
	case $sub in
	list)
		as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --themes" | awk -F '\t' 'BEGIN {printf "%-24s %-8s %-10s %s\n", "THEME", "VERSION", "FROM", "STATUS"} {printf "%-24s %-8s %-10s %s\n", $1, $2, $3, $4}' ;;
	refresh) catalog_fetch theme ;;
	add)
		[ -f "${1:-}" ] || die "theme add: give a .tar.gz of a theme's folder, or of several"
		catalog_add theme "$1" ;;
	install|update)
		n=${1:-}
		if [ "$sub" = update ] && [ "$n" = --all ]; then PINS='' update_all theme; return $?; fi
		echo "$n" | grep -Eq '^[a-z][a-z0-9-]{1,31}$' || die "theme $sub: give the theme's name (blowfishctl theme add FILE puts one in the list)"
		if [ "$sub" = update ]; then [ -d "$THEMES_EXTRA/$n" ] || die "$n isn't installed"; fi
		if [ "$sub" = install ] && [ -d "$THEMES_EXTRA/$n" ]; then die "$n is already installed; use: blowfishctl theme update $n"; fi
		(catalog_fetch theme quiet) || log "the themes couldn't be fetched; using the list as it is"
		[ -f "$THEMES_CATALOG/$n/theme.json" ] || die "there's no theme called $n in the list (upload it on the Themes tab, or: blowfishctl theme add FILE)"
		theme_put "$THEMES_CATALOG/$n" ;;
	remove)
		n=${1:-}
		echo "$n" | grep -Eq '^[a-z][a-z0-9-]{1,31}$' || die "theme remove: give the theme's name"
		[ -d "$THEMES_EXTRA/$n" ] || die "$n isn't an installed theme"
		as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --theme-forget $n" >&2 || die "$n wasn't removed (see above)"
		mv "$THEMES_EXTRA/$n" "$THEMES_EXTRA/.$n.removed.$(date -u +%Y%m%dT%H%M%SZ)"
		build_web "$APP" "$WEB.new"; rm -rf "$WEB"; mv "$WEB.new" "$WEB"
		log "$n removed (kept in $THEMES_EXTRA/.$n.removed.*)" ;;
	*) die "theme: use list, add, refresh, install, update or remove" ;;
	esac
}
# ---- The admin's System screen: update, roll back and back up --------------
# The admin service (no root) files a request in $SYS/requests; root's crontab
# runs `blowfishctl requests` every minute, which carries it out and writes
# the result and its log in $SYS/results. A release uploaded in the admin is
# copied where only root can write before `blowfishctl update` installs it
# (with its tests first, and the previous release put back if it fails).
# The System spool's folders: requests/ and releases/ the admin writes,
# results/ and downloads/ only root writes (the admin can read them).
system_dirs() {
	adm=$(account admin)
	install -d -o root -g "$adm" -m 0750 "$SYS"
	install -d -o "$adm" -g "$adm" -m 0750 "$SYS/requests" "$SYS/releases"
	install -d -o root -g "$adm" -m 0750 "$SYS/results" "$SYS/downloads"
}
# The add-ons and themes an update-all request pinned, one "TYPE NAME
# VERSION" a line, only well-formed ones.
json_pins() {   # json_pins FILE: an update-all request's pinned versions, one "TYPE NAME VERSION" a line
	perl -MJSON::PP -e 'open my $f,"<",$ARGV[0] or exit 1; local $/; my $d=eval {decode_json(<$f>)}; exit 0 unless ref $d eq "HASH" && ref $d->{pins} eq "ARRAY";
		for (@{$d->{pins}}) {print "$1 $2 $3\n" if defined && /\A(addon|theme):([a-z][a-z0-9-]{1,31}):([0-9]+(?:\.[0-9]+){1,3})\z/}' "$1"
}
# An updates_from request's address: a Repositories address (address_ok's
# shape: https, a host, plain path words) or "none"; nothing otherwise.
json_address() {   # json_address FILE
	perl -MJSON::PP -e 'open my $f,"<",$ARGV[0] or exit 1; local $/; my $d=eval {decode_json(<$f>)}; exit 0 unless ref $d eq "HASH"; my $v=$d->{address} // "";
		print $v if $v eq "none" || $v =~ m{\Ahttps://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~-]+)*/?\z} && length($v)<=300' "$1"
}
# A request's field, only when it's a plain word.
json_word() {   # json_word FILE KEY
	perl -MJSON::PP -e 'open my $f,"<",$ARGV[0] or exit 1; local $/; my $d=eval {decode_json(<$f>)}; exit 1 unless ref $d eq "HASH"; my $v=$d->{$ARGV[1]} // ""; print $v if $v =~ /\A[A-Za-z0-9_.-]{1,80}\z/' "$1" "$2"
}
# Marks a result file as root's, readable by the admin service.
root_file() {   # root_file FILE: readable by the admin service, writable only by root
	chown "root:$(account admin)" "$1"; chmod 0640 "$1"
}
# Writes a request's result file (running, done or failed).
request_result() {   # request_result ID STATUS ACTION BY [ARG]
	f=$SYS/results/$1.json
	printf '{"id":"%s","status":"%s","action":"%s","by":"%s","arg":"%s","at":%s}\n' "$1" "$2" "$3" "$4" "${5:-}" "$(date +%s)" >"$f.tmp"
	root_file "$f.tmp"; mv "$f.tmp" "$f"
}
# What the System screen shows about the server: the live and kept releases,
# nightly backups and free space, and when the requests last ran.
system_state() {
	kept='' kept_v=''
	# shellcheck disable=SC2045  # release folders are timestamps this script made
	for entry in $(ls -1t "$STORE/releases" 2>/dev/null); do
		case $entry in failed-*|rolled-back-*) continue ;; esac
		[ -d "$STORE/releases/$entry/app" ] && kept="$kept $entry" && kept_v="$kept_v $(release_version "$STORE/releases/$entry/app")"
	done
	# Nightly backups: how many are kept, the space they take and what's left, and the last run.
	n_count=0 n_kb=0
	for b in $(nightly_names); do
		n_count=$((n_count + 1)); n_kb=$((n_kb + $(du -k "$STORE/$b" | cut -f1)))
	done
	free_kb=$(df -Pk "$STORE" 2>/dev/null | awk 'NR==2 {print $4}')
	perl -MJSON::PP -e 'my ($st,$at,$msg)=split / /,$ARGV[4],3; print JSON::PP->new->canonical->encode({release=>$ARGV[0],kept=>[grep {length} split / /,$ARGV[1]],off=>0+$ARGV[2],checked=>time,version=>$ARGV[7],kept_versions=>[grep {length} split / /,$ARGV[8]],
		nightly=>{count=>0+$ARGV[3],bytes=>1024*($ARGV[5]||0),status=>$st//"",at=>0+($at//0),message=>$msg//""},free=>1024*($ARGV[6]||0),updates_from=>$ARGV[9]//"",releases_url=>$ARGV[10]//""}),"\n"' \
		"$(cat "$APP/.release" 2>/dev/null || echo unknown)" "$kept" "$([ -f "/etc/$NAME-no-system" ] && echo 1 || echo 0)" \
		"$n_count" "$(cat "$STORE/nightly.last" 2>/dev/null || true)" "$n_kb" "${free_kb:-0}" "$(release_version "$APP")" "$kept_v" \
		"$(updates_from)" "$(head -1 "/etc/$NAME-releases-url" 2>/dev/null || true)" >"$SYS/results/state.json.tmp"
	root_file "$SYS/results/state.json.tmp"; mv "$SYS/results/state.json.tmp" "$SYS/results/state.json"
}
# The newest backup goes in the admin's downloads (a hard link: no extra space); three are kept there.
# Offers the newest backup for download on the System screen (a hard link,
# so it takes no extra space; the three newest are offered).
offer_backup() {
	# shellcheck disable=SC2012  # backup names are timestamps this script made
	latest=$(ls -1t "$STORE"/"$NAME"-[0-9]*T[0-9]*Z.tar.gz 2>/dev/null | head -1)
	[ -n "$latest" ] || return 0
	to=$SYS/downloads/$(basename "$latest")
	ln -f "$latest" "$to" 2>/dev/null || cp -p "$latest" "$to"
	root_file "$to"
	# shellcheck disable=SC2012
	ls -1t "$SYS/downloads"/*.tar.gz 2>/dev/null | tail -n +4 | while IFS= read -r old; do rm -f "$old"; done
	log "the backup can be downloaded from the admin's System screen"
}
# Carries out one request from the System screen, in a subshell so a failure
# ends only this request. An uploaded release or archive is first copied
# where only root can write (so the admin can't change it while it's being
# installed), and its sha256 is logged. Every argument is checked against a
# strict pattern before it's used.
run_request() {   # run_request ID ACTION ARG (in a subshell: die ends only the request)
	case $2 in
	update)
		rel=$SYS/releases/$1.tar.gz
		[ -f "$rel" ] && [ ! -L "$rel" ] || die "the uploaded release is missing"
		work=$(mktemp -d /var/tmp/blowfish-release.XXXXXXXXXX)
		cp "$rel" "$work/blowfishcms.tar.gz"; rm -f "$rel"
		log "sha256 of the uploaded release: $(sha256 -q "$work/blowfishcms.tar.gz")"
		rc=0; BLOWFISH_PROGRESS=$SYS/results/$1.progress sh "$0" update "$work/blowfishcms.tar.gz" || rc=$?
		rm -rf "$work"; return $rc ;;
	rollback) sh "$0" rollback ;;
	backup) sh "$0" backup && offer_backup ;;
	backup_remove)
		printf '%s' "$3" | grep -Eq "^$NAME-[0-9]{8}T[0-9]{6}Z\\.tar\\.gz\$" || die "no such backup"
		rm -f "$SYS/downloads/$3" "$STORE/$3" "$STORE/$3.sha256"
		log "removed the backup $3" ;;
	addons_update_all) update_all addon ;;
	themes_update_all) update_all theme ;;
	updates_all) update_all addon theme ;;
	addons_add|themes_add)
		up=$SYS/releases/$1.tar.gz
		[ -f "$up" ] && [ ! -L "$up" ] || die "the uploaded archive is missing"
		work=$(mktemp -d /var/tmp/blowfish-upload.XXXXXXXXXX)
		cp "$up" "$work/upload.tar.gz"; rm -f "$up"
		log "sha256 of the uploaded archive: $(sha256 -q "$work/upload.tar.gz")"
		rc=0; (catalog_add "${2%s_add}" "$work/upload.tar.gz") || rc=$?
		rm -rf "$work"; return $rc ;;
	addons_refresh) sh "$0" addon refresh ;;
	themes_refresh) sh "$0" theme refresh ;;
	releases_refresh) releases_fetch ;;
	updates_from)
		# Set on the System screen: the address (checked again as it's read), then a first look.
		[ -n "${ADDRESS:-}" ] || die "that isn't an address updates can come from"
		sh "$0" updates-from "$ADDRESS"
		if [ "$ADDRESS" != none ]; then (releases_fetch) || log "the address is kept; no release could be read there yet (see above)"; fi ;;
	updates_check) check_updates ;;
	update_fetch)
		printf '%s' "$3" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || die "no such release"
		work=$(mktemp -d /var/tmp/blowfish-release.XXXXXXXXXX)
		(release_download "$3" "$work") || { rm -rf "$work"; die "release $3 wasn't installed"; }
		rc=0; BLOWFISH_PROGRESS=$SYS/results/$1.progress sh "$0" update "$work/blowfishcms.tar.gz" || rc=$?
		rm -rf "$work"; return $rc ;;
	theme_install|theme_update|theme_remove)
		printf '%s' "$3" | grep -Eq '^[a-z][a-z0-9-]{1,31}$' || die "no such theme"
		sh "$0" theme "${2#theme_}" "$3" ;;
	addon_install|addon_update|addon_enable|addon_disable|addon_remove)
		printf '%s' "$3" | grep -Eq '^[a-z][a-z0-9]{1,19}$' || die "no such add-on"
		if [ "$2" = addon_install ]; then sh "$0" addon install "$3" && sh "$0" addon enable "$3"
		elif [ "$2" = addon_remove ]; then
			# From the admin, an add-on that's on is switched off first.
			if addons_on | grep -q "^$3 "; then sh "$0" addon disable "$3" || exit 1; fi
			sh "$0" addon remove "$3"
		else sh "$0" addon "${2#addon_}" "$3"; fi ;;
	*) die "unknown request: $2" ;;
	esac
}
# ---- Mail from add-ons --------------------------------------------------------
# Only the contact form's account can read the Postmark token, so other
# services write mail to send (a new order, a newsletter) as files in an
# outbox in their own folder. Every minute this moves them into the contact
# folder's mailq/, readable by that account alone, and has it send them. A
# file is moved only if it's a plain file with one link, owned by whoever owns
# the outbox, so a service can't hand over someone else's file.
MAILQ=$CONTACT/mailq
# See above. Then, if anything is queued, has the contact account send it
# (with a lock, so two runs don't send the same message twice).
mail_relay() {
	contact=$(account contact)
	for box in "$DATA/outbox" "$ADDON_DATA"/*/outbox; do
		[ -d "$box" ] && [ ! -L "$box" ] || continue
		# shellcheck disable=SC2012
		owner=$(ls -lnd "$box" | awk '{print $3}')
		src=$(basename "$(dirname "$box")")
		for f in "$box"/*.json; do
			[ -f "$f" ] && [ ! -L "$f" ] || continue
			base=$(basename "$f")
			case $base in *[!A-Za-z0-9._-]*) rm -f "$f"; continue ;; esac
			# shellcheck disable=SC2012
			links=$(ls -ln "$f" | awk '{print $2}')
			# shellcheck disable=SC2012
			fowner=$(ls -ln "$f" | awk '{print $3}')
			if [ "$links" != 1 ] || [ "$fowner" != "$owner" ]; then log "a queued message in $box was refused (not the outbox owner's own file)"; rm -f "$f"; continue; fi
			if [ "$(wc -c <"$f")" -gt 1048576 ]; then rm -f "$f"; log "a queued message over 1 MB in $box was dropped"; continue; fi
			[ -d "$MAILQ" ] || install -d -o "$contact" -g "$(account public)" -m 0700 "$MAILQ"
			mv "$f" "$MAILQ/$src-$base" && chown "$contact" "$MAILQ/$src-$base" && chmod 0600 "$MAILQ/$src-$base"
		done
	done
	ls "$MAILQ"/*.json >/dev/null 2>&1 || return 0
	mlock=$STORE/mail.lock
	mkdir "$mlock" 2>/dev/null || { [ -n "$(find "$mlock" -maxdepth 0 -mmin +30 2>/dev/null)" ] && rmdir "$mlock" && mkdir "$mlock"; } || return 0
	as_user "$contact" "/usr/bin/perl '$APP/cgi-bin/site.pl' --mail-send" >/dev/null 2>&1 || true
	rmdir "$mlock"
}
# ---- Videos from add-ons ------------------------------------------------------
# Live hands each saved stream to the Videos library as a file in its own
# data folder's videos/ (NAME.mp4, with its note NAME.json). Every minute
# this moves them into the admin's videos-in/, which only the admin's
# account can read, and has that account add them to the library
# (site.pl --import-videos, which joins a stream's pieces into an ordinary
# MP4). As with mail, a file is moved only if it's a plain file with one
# link, owned by whoever owns the folder it's in. A recording an add-on never
# finished (in its rec/, untouched for 15 minutes) is moved the same way.
# One run at a time: moving and joining a long stream can outlast a minute.
VIDEOS_IN=$DATA/videos-in
video_relay() {
	vlock=$STORE/videos.lock
	mkdir "$vlock" 2>/dev/null || { [ -n "$(find "$vlock" -maxdepth 0 -mmin +360 2>/dev/null)" ] && rmdir "$vlock" && mkdir "$vlock"; } || return 0
	admin=$(account admin)
	for box in "$ADDON_DATA"/*/videos "$ADDON_DATA"/*/rec; do
		if [ ! -d "$box" ] || [ -L "$box" ]; then continue; fi
		# shellcheck disable=SC2012
		owner=$(ls -lnd "$box" | awk '{print $3}')
		src=$(basename "$(dirname "$box")")
		for f in "$box"/*.mp4; do
			if [ ! -f "$f" ] || [ -L "$f" ]; then continue; fi
			stem=$(basename "$f" .mp4)
			case $stem in *[!A-Za-z0-9_-]*) continue ;; esac
			case $box in */rec) [ -n "$(find "$f" -maxdepth 0 -mmin +15 2>/dev/null)" ] || continue ;; esac
			note=$box/$stem.json
			if [ ! -f "$note" ] || [ -L "$note" ]; then continue; fi
			ok=1
			for x in "$f" "$note"; do
				# shellcheck disable=SC2012
				[ "$(ls -ln "$x" | awk '{print $2, $3}')" = "1 $owner" ] || ok=''
			done
			if [ -z "$ok" ] || [ "$(wc -c <"$note")" -gt 65536 ]; then log "a video in $box was refused (not the folder owner's own file)"; rm -f "$f" "$note"; continue; fi
			[ -d "$VIDEOS_IN" ] || install -d -o "$admin" -g "$(account public)" -m 0700 "$VIDEOS_IN"
			# The note first: the admin takes a video only with its note beside it.
			if ! mv "$note" "$VIDEOS_IN/$src-$stem.json" || ! mv "$f" "$VIDEOS_IN/$src-$stem.mp4"; then log "a video from $src couldn't be moved (is the disk full?)"; continue; fi
			chown "$admin" "$VIDEOS_IN/$src-$stem.json" "$VIDEOS_IN/$src-$stem.mp4"
			chmod 0600 "$VIDEOS_IN/$src-$stem.json" "$VIDEOS_IN/$src-$stem.mp4"
			log "a video from $src is waiting for the Videos library ($src-$stem.mp4)"
		done
	done
	if ls "$VIDEOS_IN"/*.mp4 >/dev/null 2>&1 && grep -q -- '--import-videos' "$APP/cgi-bin/site.pl"; then
		# At low priority: joining a long stream copies gigabytes, and the site comes first.
		as_user "$admin" "/usr/bin/nice -n 15 /usr/bin/perl '$APP/cgi-bin/site.pl' --import-videos" >>"/var/log/$NAME-videos.log" 2>&1 || true
	fi
	# Videos that couldn't be added are kept for a week, for a look.
	find "$VIDEOS_IN/failed" -type f -mtime +7 -exec rm -f {} + 2>/dev/null || true
	rmdir "$vlock"
}
# ---- Hand-overs from add-ons' services ----------------------------------------
# An add-on's service can't write the catalogue, so it hands its admin side
# what to do as JSON files in its data folder's to-admin/ (the Store:
# Printful's products). Every minute this moves them into the admin's
# addons-in/ (as NAME-FILE.json), readable by the admin's account alone, and
# has that account pass each to its add-on (site.pl --addons-in). As with
# mail, a file is moved only if it's a plain file with one link, owned by
# whoever owns the folder it's in.
ADDONS_IN=$DATA/addons-in
handover_relay() {
	admin=$(account admin)
	for box in "$ADDON_DATA"/*/to-admin; do
		if [ ! -d "$box" ] || [ -L "$box" ]; then continue; fi
		# shellcheck disable=SC2012
		owner=$(ls -lnd "$box" | awk '{print $3}')
		src=$(basename "$(dirname "$box")")
		for f in "$box"/*.json; do
			if [ ! -f "$f" ] || [ -L "$f" ]; then continue; fi
			base=$(basename "$f")
			case $base in *[!A-Za-z0-9._-]*) rm -f "$f"; continue ;; esac
			# shellcheck disable=SC2012
			if [ "$(ls -ln "$f" | awk '{print $2, $3}')" != "1 $owner" ]; then log "a hand-over in $box was refused (not the folder owner's own file)"; rm -f "$f"; continue; fi
			if [ "$(wc -c <"$f")" -gt 8388608 ]; then rm -f "$f"; log "a hand-over over 8 MB in $box was dropped"; continue; fi
			[ -d "$ADDONS_IN" ] || install -d -o "$admin" -g "$(account public)" -m 0700 "$ADDONS_IN"
			mv "$f" "$ADDONS_IN/$src-$base" && chown "$admin" "$ADDONS_IN/$src-$base" && chmod 0600 "$ADDONS_IN/$src-$base"
		done
	done
	ls "$ADDONS_IN"/*.json >/dev/null 2>&1 || return 0
	grep -q -- '--addons-in' "$APP/cgi-bin/site.pl" || return 0
	hlock=$STORE/addons-in.lock
	mkdir "$hlock" 2>/dev/null || { [ -n "$(find "$hlock" -maxdepth 0 -mmin +30 2>/dev/null)" ] && rmdir "$hlock" && mkdir "$hlock"; } || return 0
	as_user "$admin" "/usr/bin/perl '$APP/cgi-bin/site.pl' --addons-in" 2>&1 || true
	# Hand-overs that failed are kept for a week, for a look.
	find "$ADDONS_IN/failed" -type f -mtime +7 -exec rm -f {} + 2>/dev/null || true
	rmdir "$hlock"
}
# blowfishctl requests (root's crontab, every minute): relays queued mail,
# add-ons' videos and their hand-overs, then, unless the System screen is turned off, takes the
# lock and carries out each waiting request in turn, logging each one and
# writing its result. Old results (60 days) and abandoned uploads (a day) are
# cleared.
cmd_requests() {
	(mail_relay) || log "queued mail couldn't be relayed"
	(video_relay) || log "add-ons' videos couldn't be relayed"
	(handover_relay) || log "add-ons' hand-overs couldn't be relayed"
	[ -d "$SYS/requests" ] || exit 0
	# The server's owner can turn the System screen off: doas touch /etc/blowfishcms-no-system
	if [ -f "/etc/$NAME-no-system" ]; then
		rm -f "$SYS"/requests/*.json "$SYS"/releases/*.tar.gz 2>/dev/null; system_state; exit 0
	fi
	lock=$STORE/requests.lock
	if ! mkdir "$lock" 2>/dev/null; then
		# A lock older than three hours was left by a run that died.
		[ -n "$(find "$lock" -maxdepth 0 -mmin +180 2>/dev/null)" ] || exit 0
		rmdir "$lock" && mkdir "$lock" || exit 0
	fi
	trap 'rmdir "$lock"' EXIT
	system_state
	for req in "$SYS"/requests/*.json; do
		[ -f "$req" ] && [ ! -L "$req" ] || continue
		id=$(basename "$req" .json)
		printf '%s' "$id" | grep -Eq '^[a-f0-9]{32}$' || { rm -f "$req"; continue; }
		action=$(json_word "$req" action); by=$(json_word "$req" by); arg=$(json_word "$req" arg)
		PINS=$(json_pins "$req" || true); ADDRESS=$(json_address "$req" || true)
		rm -f "$req"
		out=$SYS/results/$id.log; : >"$out"; root_file "$out"
		request_result "$id" running "$action" "$by" "$arg"
		log "$action $arg requested by $by ($id)"
		if (PINS=$PINS ADDRESS=$ADDRESS run_request "$id" "$action" "$arg") >>"$out" 2>&1; then request_result "$id" "done" "$action" "$by" "$arg"
		else request_result "$id" failed "$action" "$by" "$arg"; fi
		system_state
	done
	# Results are kept for 60 days; uploads that were never requested for a day.
	find "$SYS/results" -name '*.json' ! -name state.json -mtime +60 -exec rm -f {} + 2>/dev/null
	find "$SYS/results" -name '*.log' -mtime +60 -exec rm -f {} + 2>/dev/null
	find "$SYS/results" -name '*.progress' -mtime +60 -exec rm -f {} + 2>/dev/null
	find "$SYS/releases" -type f -mtime +1 -exec rm -f {} + 2>/dev/null
	return 0
}
# ---- Nightly backups ------------------------------------------------------------
# Root's crontab runs `blowfishctl nightly` once a night. It makes the same
# backup as `blowfishctl backup` and keeps the newest N of its own (an owner
# sets N, or turns it off, on the System screen); backups made by hand and the
# snapshots updates take are never removed. $STORE/nightly.list names the
# backups it made, oldest first; $STORE/nightly.last says how the last run went.
# The nightly backups still on the server, oldest first (an owner may have deleted some).
nightly_names() {
	grep -E "^$NAME-[0-9]{8}T[0-9]{6}Z\\.tar\\.gz\$" "$STORE/nightly.list" 2>/dev/null | while IFS= read -r b; do
		[ ! -f "$STORE/$b" ] || printf '%s\n' "$b"
	done
}
# Records how the nightly backup went, for the System screen.
nightly_note() {   # nightly_note STATUS MESSAGE
	printf '%s %s %s\n' "$1" "$(date +%s)" "$2" >"$STORE/nightly.last"
	[ ! -d "$SYS/results" ] || system_state
}
# blowfishctl nightly (root's crontab): checks for updates, then (unless
# nightly backups are off) waits for the requests lock so it never runs
# during an update, checks there's room (twice the last backup's size), makes
# the backup, offers it for download, and removes the oldest nightly backups
# beyond the number to keep.
cmd_nightly() {
	# Every night: new releases of BlowfishCMS, the add-ons and the themes, and an alert about anything new.
	if mkdir "$STORE/requests.lock" 2>/dev/null; then
		(check_updates) || log "tonight's check for updates didn't finish"
		rmdir "$STORE/requests.lock"
	fi
	plan=$(as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --backup-plan" 2>/dev/null) || plan='on 14'
	state=${plan%% *} keep=${plan##* }
	case $keep in ''|*[!0-9]*) keep=14 ;; esac
	{ [ "$keep" -ge 1 ] && [ "$keep" -le 30 ]; } || keep=14
	if [ "$state" != on ]; then log "nightly backups are turned off"; nightly_note off "turned off on the System screen"; return 0; fi
	# The same lock as the System screen's requests: a backup never runs during an update.
	lock=$STORE/requests.lock tries=0
	until mkdir "$lock" 2>/dev/null; do
		tries=$((tries + 1))
		[ "$tries" -le 120 ] || { nightly_note failed "the server was busy with another request all night"; die "nightly backup: still busy after an hour"; }
		sleep 30
	done
	trap 'rmdir "$lock"' EXIT
	# Room for another backup, with a margin: twice the size of the last one.
	last=$(nightly_names | tail -1)
	need_kb=$([ -n "$last" ] && [ -f "$STORE/$last" ] && du -k "$STORE/$last" | cut -f1 || echo 0)
	free_kb=$(df -Pk "$STORE" | awk 'NR==2 {print $4}')
	if [ "$((need_kb * 2))" -gt "${free_kb:-0}" ]; then
		nightly_note failed "not enough free disk space for another backup; delete some, or keep fewer"
		die "nightly backup skipped: ${free_kb:-0} KB free, about $need_kb KB needed"
	fi
	if ! sh "$0" backup; then nightly_note failed "the backup failed; see /var/log/$NAME-backup.log"; die "nightly backup failed"; fi
	# shellcheck disable=SC2012  # backup names are timestamps this script made
	made=$(ls -1t "$STORE"/"$NAME"-[0-9]*T[0-9]*Z.tar.gz 2>/dev/null | head -1)
	[ -n "$made" ] && basename "$made" >>"$STORE/nightly.list"
	[ ! -d "$SYS/downloads" ] || offer_backup
	# Keep the newest $keep of the nightly backups.
	count=$(nightly_names | wc -l | tr -d ' ')
	if [ "$count" -gt "$keep" ]; then
		nightly_names | head -n "$((count - keep))" | while IFS= read -r old; do
			rm -f "$STORE/$old" "$STORE/$old.sha256" "$SYS/downloads/$old"
			log "removed the old nightly backup $old"
		done
		nightly_names | tail -n "$keep" >"$STORE/nightly.list.tmp"; mv "$STORE/nightly.list.tmp" "$STORE/nightly.list"
	fi
	nightly_note "done" "kept the newest $keep"
}
# blowfishctl backup [--with-secrets]: a .tar.gz in /var/backups/blowfishcms
# with the media, settings, code, contact folder, httpd configuration, add-on
# data, installed add-ons and site files, plus safe snapshots of the
# databases and a RESTORE.txt saying how to put it back. Its sha256 is saved
# beside it. --with-secrets also writes a separate archive of the tokens and
# keys, which the ordinary backup leaves out.
cmd_backup() {
	with_secrets=0
	[ "${1:-}" = --with-secrets ] && with_secrets=1
	stamp=$(date -u +%Y%m%dT%H%M%SZ)
	work=$(mktemp -d /var/tmp/blowfish-backup.XXXXXXXXXX)
	trap 'rm -rf "$work"' EXIT
	install -d -m 0700 "$work/_backup"
	snapshot_db "$DB" "$work/_backup/catalog.sqlite"
	snapshot_db "$COMMENTS/comments.sqlite" "$work/_backup/comments.sqlite"
	snapshot_db "$COMMENTS/analytics/analytics.sqlite" "$work/_backup/analytics.sqlite"
	snapshot_db "$DATA/admin/accounts.sqlite" "$work/_backup/accounts.sqlite"
	crontab -u root -l >"$work/_backup/root.crontab" 2>/dev/null || true
	pkg_info -mz >"$work/_backup/packages.txt" 2>/dev/null || true
	cat >"$work/_backup/RESTORE.txt" <<EOF
Restoring a BlowfishCMS backup ($stamp) on a fresh OpenBSD server:
  1. Unpack a release and run: doas ./bin/blowfishctl install --domain ... --admin ...
     (same domain and admin account as before).
  2. doas rcctl stop blowfish_public blowfish_admin blowfish_contact blowfish_comments
  3. doas tar -xzpf $NAME-$stamp.tar.gz -C /     (media, settings, code)
  4. doas install -o _bfadmin -g _bfpublic -m 0640 /_backup/catalog.sqlite $DB
     doas install -o _bfcomments -g _bfpublic -m 0644 /_backup/comments.sqlite $COMMENTS/comments.sqlite
     doas install -o _bfcomments -g _bfpublic -m 0600 /_backup/analytics.sqlite $COMMENTS/analytics/analytics.sqlite  (if it's there)
     doas install -o _bfadmin -g _bfadmin -m 0600 /_backup/accounts.sqlite $DATA/admin/accounts.sqlite  (users' passwords and emails; if it's there)
  5. doas blowfishctl password; doas blowfishctl mail-token  (or unpack the secrets archive)
  6. doas blowfishctl restart; doas rm -rf /_backup
EOF
	out=$STORE/$NAME-$stamp.tar.gz
	# Add-on data, add-ons installed apart from releases and the site's own files, when there are any.
	extra='' extra_secrets=''
	[ ! -d "$ADDON_DATA" ] || extra="$extra ${ADDON_DATA#/}"
	[ ! -d "$ADDONS_EXTRA" ] || extra="$extra ${ADDONS_EXTRA#/}"
	[ ! -d "$SITE_FILES" ] || extra="$extra ${SITE_FILES#/}"
	[ ! -d "$ADDON_SECRETS" ] || extra_secrets=${ADDON_SECRETS#/}
	[ ! -d "$SESSION" ] || extra_secrets="$extra_secrets ${SESSION#/}"
	# shellcheck disable=SC2086
	tar -czpf "$out" -C / \
		"${MEDIA#/}" "${CONF#/}" "${APP#/}" "${CONTACT#/}" "${HTTPD_SITE#/}" \
		$extra \
		-C "$work" _backup
	chmod 0600 "$out"
	sha256 -q "$out" >"$out.sha256"
	log "backup: $out ($(du -h "$out" | cut -f1))"
	if [ "$with_secrets" -eq 1 ]; then
		sec=$STORE/$NAME-secrets-$stamp.tar.gz
		# shellcheck disable=SC2086
		tar -czpf "$sec" -C / "${SECRETS#/}" "${DATA#/}/admin/csrf.key" "${COMMENTS#/}/private" $extra_secrets
		chmod 0600 "$sec"
		log "secrets: $sec (keep it somewhere safe and private)"
	fi
}

# The command line: the first word picks the command; the rest are its
# arguments.
cmd=${1:-}
[ $# -eq 0 ] || shift
# shellcheck disable=SC2012
case $cmd in
install) cmd_install "$@" ;;
update) cmd_update "$@" ;;
rollback) cmd_rollback ;;
releases)
	echo "live: $(release_version "$APP") (installed $(cat "$APP/.release" 2>/dev/null || echo "at an unknown time"))"
	# shellcheck disable=SC2045  # release folders are timestamps this script made
	for r in $(ls -1t "$STORE/releases" 2>/dev/null); do
		if [ -d "$STORE/releases/$r/app" ]; then echo "kept: $(release_version "$STORE/releases/$r/app") (replaced by the update of $r)"; else echo "kept: $r (catalogue snapshot only)"; fi
	done ;;
status) cmd_status ;;
restart) restart_services ;;
httpd)
	# Also puts back the login page's session key, its group and permissions if they went missing.
	if [ -n "$(session_setup)" ]; then
		log "the sign-in session key was set up again"
		services_install
		restart_services || log "a service failed to restart: see blowfishctl status"
	fi
	system_dirs; media_folders; addon_files_dirs; catalog_lists_write; catalog_bundled "$APP"; cron_install; install_tool "$APP"
	precompress "$WEB"
	httpd_apply "$(httpd_mode)"; log "httpd configuration is current" ;;
unlock) rm -f "$DATA/admin/logins.json"; log "failed sign-ins cleared; you can sign in again" ;;
requests) cmd_requests ;;
nightly) cmd_nightly ;;
mfa-off)
	user=${1:-}
	printf '%s' "$user" | grep -Eq '^[a-z_][a-z0-9_.-]{0,31}$' || die "mfa-off: give the admin user's name"
	as_user "$(account admin)" "/usr/bin/perl '$APP/cgi-bin/site.pl' --mfa-off '$user'" ;;
password) set_password "$@" ;;
mail-token) set_mail_token ;;
certificate) certificate || die "no certificate: check that the domain points at this server (see the messages above)" ;;
migrate) migrate_with "$APP" ;;
backup) cmd_backup "$@" ;;
addon) cmd_addon "$@" ;;
theme) cmd_theme "$@" ;;
check-updates) check_updates ;;
updates-from) cmd_updates_from "$@" ;;
places) places_fetch now ;;
files)
	install -d -o root -g wheel -m 0755 "$SITE_FILES"
	build_web "$APP" "$WEB.new"; rm -rf "$WEB"; mv "$WEB.new" "$WEB"
	log "web root rebuilt with the site's own files from $SITE_FILES" ;;
""|-h|--help|help) usage ;;
*) usage >&2; die "unknown command: $cmd" ;;
esac
