#!/bin/bash
# Copyright 2026 FairSSL A/S - fairssl.dk, fairssl.se, sslbrain.com
# Newest version and guide: https://sslbrain.com/free-tls-scripts/linux-post-quantum-tls-nginx-apache-haproxy/
# Installs on: nginx, Apache httpd and HAProxy on Linux
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
# .SYNOPSIS
#   Reads the TLS and post-quantum settings of nginx, Apache and HAProxy, sets the recommended ones with
#   the hybrid group X25519MLKEM768, and puts everything back on request.
# .DESCRIPTION
#   What it does:
#   - Without options it only reads: the TLS library, every site and listener, the protocols, cipher
#     suites and groups the configuration sets, and what a handshake agrees on, with a rating, a
#     verdict and the next step.
#   - With --apply it sets the Mozilla intermediate profile and post-quantum key exchange for the parts
#     you choose, in one place of its own. --dry-run shows the change and writes nothing.
#   - Tests the configuration before a graceful reload, and puts the previous settings back when the
#     reload or the TLS handshake fails.
#   - Keeps what was there before; --undo puts back exactly that.
#   - Never restarts a server, and sends nothing anywhere.
#
#   Requires:
#   - nginx, Apache httpd 2.4 or HAProxy on Linux, with bash 4.2 or later, awk and openssl. Run as root.
#   - Post-quantum key exchange needs the server to run on OpenSSL 3.5 or later (Debian 13, Ubuntu 26.04,
#     RHEL 10.1). On an older OpenSSL the script says so and sets protocols and cipher suites.
#
#   Commands:
#   - Read the server. Nothing is changed.
#         sudo ./set-linux-server-tls
#   - See what the recommended settings would change.
#         sudo ./set-linux-server-tls --apply --dry-run
#   - Set them.
#         sudo ./set-linux-server-tls --apply
#   - Writes the report as HTML or JSON to a file.
#         sudo ./set-linux-server-tls --report html --report-file /root/tls-report.html
#   - Switches on post-quantum key exchange only, and leaves protocols and cipher suites alone.
#         sudo ./set-linux-server-tls --apply --parts groups
#   - Sets protocols and cipher suites and leaves the groups alone.
#         sudo ./set-linux-server-tls --apply --pqc ignore
#   - Accepts only TLS 1.3 with a post-quantum hybrid group. Clients without one can no longer connect.
#         sudo ./set-linux-server-tls --apply --pqc only
#   - Puts back everything the script changed.
#         sudo ./set-linux-server-tls --undo
#
#   How it decides (details):
#   The script uses the same code as the sslbrain agents for nginx, Apache and HAProxy to find the
#   server, read its configuration, write the settings, reload and check, so the script and sslbrain
#   give the same answer on the same server.
#
#   Reading (no options). Nothing is written. For each product that is installed the report shows its
#   version, the TLS library it runs on, the TLS directives of its configuration with file and line,
#   and for each TLS site or listener what a local handshake gives: TLS 1.3 and the group it agrees
#   on, TLS 1.2, whether TLS 1.0 or 1.1 is answered, and whether a cipher suite outside the profile
#   is accepted. The verdict for each item is one of:
#   - OK: already active
#   - APPLY: the script can set it; the line gives the command
#   - UPGRADE: the TLS library is older than OpenSSL 3.5 and has no post-quantum key exchange
#   - CONFIG: a site keeps a setting of its own, which the script does not change; the line names it
#   - INFO: something to know
#
#   The rating. For each site or listener that answers, the report also rates the protocols it
#   answers, each group it agrees to (the script offers them one at a time), the cipher suite it
#   chooses for TLS 1.3 and for TLS 1.2, the old kinds of cipher suite it accepts when offered one
#   kind at a time (RSA key transport, CBC, 3DES, RC4, NULL, anonymous), DHE with its size, and the
#   key and the signature hash of its certificate, with one of four levels:
#   - Use: TLS 1.3; the hybrid groups X25519MLKEM768, SecP256r1MLKEM768 and SecP384r1MLKEM1024;
#     AES-256-GCM; a certificate key of RSA 3072 or larger or ECC P-384; SHA-256 and SHA-384
#   - Works in a transition: TLS 1.2 with ECDHE and an AEAD cipher, so no cipher suite of TLS 1.2 is
#     rated higher; the curves P-384 and P-521; AES-128-GCM and ChaCha20-Poly1305; an RSA 2048 key,
#     for old equipment only
#   - Remove now (our interpretation)*: X25519 or P-256 alone, DHE, CBC cipher suites, ECC P-256 and
#     Ed25519 keys
#   - Removal recommended long ago: TLS 1.0 and TLS 1.1; RSA key transport, DHE of 1024 bits, static
#     DH; RC4, 3DES, NULL, EXPORT and anonymous suites; RSA 1024 and smaller; SHA-1 and MD5
#   * May be broken. The list is sslbrain's of 4 December 2026, after NSA's "Immediate Actions to Push
#   Toward Post-Quantum" (2 December 2026) and Mozilla's TLS guidelines; "Remove now" is our
#   interpretation of NSA's text. The recommended level keeps X25519, P-256 and P-384 after the hybrid
#   group, for clients without post-quantum key exchange, so the report says Remove now for X25519
#   and P-256 there too; --pqc only leaves only the hybrid groups. The handshakes are made by this
#   server's own openssl, so what it can no longer offer (SSL 3.0 and older, on many systems 3DES and
#   RC4) is not in the rating.
#
#   The profile (--apply) is Mozilla's intermediate configuration, version 6.0:
#   - Protocols: TLS 1.2 and TLS 1.3
#   - Cipher suites: ECDHE with AES-GCM and ChaCha20-Poly1305 for TLS 1.2; TLS 1.3 keeps its own three
#   - Groups: X25519MLKEM768, X25519, prime256v1, secp384r1
#
#   --pqc chooses the level of post-quantum key exchange:
#   - ignore: the groups are not touched
#   - when-possible: the group list with X25519MLKEM768 first, where the server runs on OpenSSL 3.5 or
#     later; elsewhere the script says why not and leaves the groups alone (default)
#   - only: TLS 1.3 only, and only the three hybrid groups of RFC 10024 (X25519MLKEM768,
#     SecP256r1MLKEM768, SecP384r1MLKEM1024). A server that cannot is not changed.
#
#   --parts chooses what is written: protocols, ciphers, groups (default: all three). A part that is
#   not chosen keeps what the script's place held for it.
#
#   Where it writes. One place per product, and nothing else in the configuration is changed:
#   - nginx: conf.d/sslbrain-tls.conf beside nginx.conf (ssl_conf_command, from nginx 1.19.4)
#   - Apache: conf-enabled/sslbrain-tls.conf (Debian, Ubuntu) or conf.d/sslbrain-tls.conf (RHEL)
#   - HAProxy: a global section between "# BEGIN sslbrain-tls" and "# END sslbrain-tls" in haproxy.cfg
#   A site, VirtualHost or bind line that sets the same thing itself keeps its own setting; the
#   script names it with file and line. A server managed by the sslbrain agent keeps the agent's
#   settings unless you add --force.
#
#   Safety. Before it writes, the configuration must pass the product's own test and a local TLS
#   handshake must answer (name the listener with --host, --port and --sni when the script cannot
#   find one; --force goes on without). After the write the configuration is tested again, the
#   product is reloaded gracefully, and the handshake must answer again and agree on the group that
#   was set. With --pqc only, a client that offers only X25519 or only TLS 1.2 must be refused, so
#   it needs an openssl 3.5 or later on the server to check with. If any of this fails, the
#   previous content is put back and reloaded. A product that is not running is not started: the
#   settings are written and tested, and apply when it starts. One --apply or --undo runs at a time.
#
#   Undo. /var/lib/sslbrain-tls (root only) keeps, per product, what the script's place held before
#   the script's first change and what the script wrote. --undo puts the first back, with the same
#   test, reload and handshake, when the place still holds what the script wrote. When someone has
#   changed it since, it is left alone and named; --undo --force puts it back anyway. Run again,
#   --undo has nothing left to do.
#
#   Exit codes:
#   - 0: done, or nothing to do
#   - 1: failed; the previous settings are back
#   - 2: refused; nothing was changed for that product
#   - 3: wrong option, not root, or no supported product found
#
# .PARAMETER --apply
#   Sets the recommended profile for the parts in --parts, at the level in --pqc.
# .PARAMETER --dry-run
#   With --apply or --undo: shows what would change and writes nothing.
# .PARAMETER --undo
#   Puts back what the script's place held before the script changed it.
# .PARAMETER --pqc
#   Post-quantum key exchange: ignore, when-possible (default) or only.
# .PARAMETER --parts
#   What --apply writes: protocols, ciphers, groups, separated by commas. Default: all three.
# .PARAMETER --product
#   Only this product: nginx, apache or haproxy. Default: every one that is installed.
# .PARAMETER --report
#   The report's format: text (default), json or html.
# .PARAMETER --report-file
#   Writes the report to this file instead of the screen.
# .PARAMETER --host
#   The address of the listener the handshake is made with. Default: the first TLS site found, on 127.0.0.1.
# .PARAMETER --port
#   The port of that listener.
# .PARAMETER --sni
#   The server name sent in the handshake.
# .PARAMETER --wait
#   Seconds to wait for the server to answer after a reload while nothing moves. Default: 300.
# .PARAMETER --force
#   Goes on where the script would refuse, and with --undo also puts back a place someone changed since.

set -euo pipefail
umask 077

SCRIPT_VERSION="1.0.0"
SCRIPT_NAME=set-linux-server-tls
PAGE=https://sslbrain.com/free-tls-scripts/linux-post-quantum-tls-nginx-apache-haproxy/
STATE_DIR=/var/lib/sslbrain-tls
LOCK=/run/sslbrain-tls.lock
# The profile: Mozilla's intermediate configuration 6.0 in OpenSSL's names, as sslbrain's catalogue has it.
PROFILE_CIPHERS=ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305
PROFILE_GROUPS=X25519MLKEM768:X25519:prime256v1:secp384r1
# The hybrid groups of RFC 10024.
HYBRID_GROUPS=X25519MLKEM768:SecP256r1MLKEM768:SecP384r1MLKEM1024
# Cipher suites outside the profile that a server with old settings accepts: RSA key exchange, CBC and 3DES.
OLD_CIPHERS=AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA:AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:DES-CBC3-SHA
MARK_OURS="written by $SCRIPT_NAME"
MARK_AGENT="on the server's page in sslbrain"
PRODUCTS="nginx apache haproxy"
FS=$'\037'

ACTION=report
LEVEL=when-possible
PARTS=protocols,ciphers,groups
ONLY_PRODUCT=""
DRY_RUN=false
FORCE=false
REPORT=text
REPORT_FILE=""
GIVEN_HOST=""
GIVEN_PORT=""
GIVEN_SNI=""
WAIT=300

say() { printf '%s\n' "$*"; }

usage() {
  awk 'NR == 1 { next } !/^#/ { exit } { sub(/^# ?/, ""); print }' "$0" \
    | awk '/^\.SYNOPSIS/ { show = 1; next } /^\.DESCRIPTION/ { next } /^\.PARAMETER/ { printf "\n%s\n", substr($0, 12); next } show { print }'
}

# ---- What the code of the sslbrain agents needs around it.

declare -A SB_IN=()
EVENTS=()
# The agents report a warning as an event of the job; here it is kept and shown to the technician.
sb_event() { EVENTS+=("$3"); }

# ---- The code of the sslbrain agents for nginx, Apache and HAProxy (nginx-ssh, apache-ssh, haproxy-ssh), unchanged.

# From the sslbrain agents' v4/lib/bash/core.sh:
# sb_json STRING: a JSON string literal. Control characters other than LF, CR and TAB become spaces.
sb_json() {
  local s="$1"
  s="${s//\\/\\\\}"; s="${s//\"/\\\"}"; s="${s//$'\n'/\\n}"; s="${s//$'\r'/\\r}"; s="${s//$'\t'/\\t}"
  s="${s//[[:cntrl:]]/ }"
  printf '"%s"' "$s"
}
# From the sslbrain agents' v4/lib/bash/service.sh:
# sb_service_reload NAME: reloads NAME; returns the reload's status (1 when the host has neither).
sb_service_reload() {
  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
    systemctl reload "$1"
  elif command -v service >/dev/null 2>&1; then
    service "$1" reload
  else
    return 1
  fi
}
# From the sslbrain agents' v4/lib/bash/tlssettings.sh:
TLSSET_PQC_GROUP=X25519MLKEM768

TLSSET_WARNINGS=""

TLSSET_EXPECT_GROUP=""

TLSSET_RELOADS=0

TLSSET_RAN_BEFORE=false   # the product's processes ran before the switch: they must run after it

tlsset_prepare() { :; }

tlsset_alive() { return 0; }

tlsset_start() { return 1; }

TLSSET_PROCESS_NAMES=""   # the product's process names as /proc/<pid>/comm shows them, set by tlsset_detect

TLSSET_MAIN_PID=""        # the parent process of the instance tlsset_detect chose, when a reload keeps it (else empty)

# _tlsset_warn CODE MESSAGE: a warning the action ends with; the first one is the result's reason.
_tlsset_warn() {
  sb_event warning "$1" "$2"
  TLSSET_WARNINGS="${TLSSET_WARNINGS:-$1$'\t'$2}"
}

# _tlsset_openssl_version TEXT: "OpenSSL 3.5.1 1 Jul 2025" -> 3.5.1; nothing for another TLS library.
_tlsset_openssl_version() {
  [[ "${1:-}" =~ OpenSSL[\ /]([0-9]+\.[0-9]+(\.[0-9]+)?) ]] && printf '%s' "${BASH_REMATCH[1]}"
  return 0
}

# _tlsset_at_least_3_5 VERSION
_tlsset_at_least_3_5() {
  local major minor
  [ -n "$1" ] || return 1
  major="${1%%.*}"; minor="${1#*.}"; minor="${minor%%.*}"
  (( 10#$major > 3 || (10#$major == 3 && 10#$minor >= 5) ))
}

# sb_tlsset_pqc_capability: TLSSET_PQC_CAPABLE, TLSSET_PQC_REASON_CODE and TLSSET_PQC_REASON from TLSSET_LIBRARY.
# X25519MLKEM768 needs OpenSSL 3.5 (ML-KEM and the hybrid groups arrived in 3.5.0); an older OpenSSL refuses the name
# and the server then does not start.
sb_tlsset_pqc_capability() {
  local version
  version="$(_tlsset_openssl_version "${TLSSET_LIBRARY:-}")"
  TLSSET_PQC_CAPABLE=false
  TLSSET_PQC_REASON_CODE=tls_library_unknown
  if [ -z "$version" ]; then
    if [ -n "${TLSSET_LIBRARY:-}" ]; then
      TLSSET_PQC_REASON="${TLSSET_PRODUCT:-The server} runs on $TLSSET_LIBRARY; sslbrain sets the group with OpenSSL 3.5 or later"
    else
      TLSSET_PQC_REASON="The TLS library ${TLSSET_PRODUCT:-the server} runs on could not be read"
    fi
  elif _tlsset_at_least_3_5 "$version"; then
    TLSSET_PQC_CAPABLE=true; TLSSET_PQC_REASON_CODE=""; TLSSET_PQC_REASON=""
  else
    TLSSET_PQC_REASON_CODE=openssl_too_old
    TLSSET_PQC_REASON="OpenSSL $version, requires 3.5"
  fi
}

# sb_tlsset_probe [s_client options]: TLSSET_PROBE_OK (a TLS 1.3 handshake with the local listener completed, or with
# TLSSET_PROBE_ANY=true a handshake of any version), TLSSET_PROBE_TLS13 (that handshake was TLS 1.3) and
# TLSSET_PROBE_GROUP (the group it agreed on). The probe's own OpenSSL must know a group to offer it, so a client
# older than 3.5 never sees X25519MLKEM768 even where the server would agree. A loopback handshake takes
# milliseconds even on a swapping server; 300 s only notices a listener that accepts and never answers.
sb_tlsset_probe() {
  local peer="$LOCAL_TLS_HOST:$LOCAL_TLS_PORT" output
  TLSSET_PROBE_OK=false
  TLSSET_PROBE_TLS13=false
  TLSSET_PROBE_GROUP=""
  command -v openssl >/dev/null 2>&1 || return 0
  [[ "$LOCAL_TLS_HOST" != *:* ]] || peer="[$LOCAL_TLS_HOST]:$LOCAL_TLS_PORT"
  local -a args=(s_client -connect "$peer" -brief)
  [ "${TLSSET_PROBE_ANY:-false}" = true ] || args+=(-tls1_3)
  [[ -z "$LOCAL_TLS_SNI" || "$LOCAL_TLS_SNI" == *'*'* ]] || args+=(-servername "$LOCAL_TLS_SNI")
  if command -v timeout >/dev/null 2>&1; then
    output="$(timeout 300 openssl "${args[@]}" "$@" </dev/null 2>&1 || true)"
  else
    output="$(openssl "${args[@]}" "$@" </dev/null 2>&1 || true)"
  fi
  [[ $'\n'"$output" != *$'\n''Protocol version: TLSv1.3'* ]] || { TLSSET_PROBE_OK=true; TLSSET_PROBE_TLS13=true; }
  [ "${TLSSET_PROBE_ANY:-false}" != true ] || [[ $'\n'"$output" != *$'\n''Protocol version: '* ]] || TLSSET_PROBE_OK=true
  # OpenSSL 3.5 prints "Negotiated TLS1.3 group:" for a hybrid group, else (and older ones always) "Peer Temp Key:"
  # or "Server Temp Key:", followed by "X25519," or, for a curve, "ECDH, prime256v1,".
  if [[ "$output" =~ Negotiated\ TLS1\.3\ group:\ ([A-Za-z0-9_-]+) ]] \
     || [[ "$output" =~ (Peer|Server)\ Temp\ Key:\ (ECDH,\ )?([A-Za-z0-9_-]+), ]]; then
    TLSSET_PROBE_GROUP="${BASH_REMATCH[${#BASH_REMATCH[@]}-1]}"
  fi
}

# _tlsset_client_knows_pqc: 0 when this host's openssl can offer X25519MLKEM768.
_tlsset_client_knows_pqc() { _tlsset_at_least_3_5 "$(_tlsset_openssl_version "$(openssl version 2>/dev/null || true)")"; }

# _tlsset_last_lines TEXT: the last three non-empty lines of a configuration test's output, on one line.
_tlsset_last_lines() {
  awk 'NF { line[++n] = $0 } END { for (i = (n > 3 ? n - 2 : 1); i <= n; i++) printf "%s ", line[i] }' <<< "$1"
}

# _tlsset_processes [PARENT]: the PIDs of the product's running processes (TLSSET_PROCESS_NAMES), one per line; with
# PARENT only that process and its children. One that has exited and waits for its parent to collect it (state Z)
# does not run.
_tlsset_processes() {
  local dir name stat
  [ -n "$TLSSET_PROCESS_NAMES" ] || return 0
  for dir in /proc/[0-9]*; do
    read -r name 2>/dev/null < "$dir/comm" || continue
    [[ " $TLSSET_PROCESS_NAMES " == *" $name "* ]] || continue
    stat="$(cat "$dir/stat" 2>/dev/null)" || continue
    stat="${stat##*) }"   # state, parent, ...
    [ "${stat%% *}" != Z ] || continue
    stat="${stat#* }"
    [ -z "${1:-}" ] || [ "${dir#/proc/}" = "$1" ] || [ "${stat%% *}" = "$1" ] || continue
    printf '%s\n' "${dir#/proc/}"
  done
}

# _tlsset_running: 0 while the product runs: the parent process of the chosen instance (TLSSET_MAIN_PID; its children
# finish their requests long after a parent that has exited, and another instance has processes of the same name),
# else any process of the product.
_tlsset_running() {
  if [ -n "$TLSSET_MAIN_PID" ]; then
    [[ $'\n'"$(_tlsset_processes "$TLSSET_MAIN_PID")"$'\n' == *$'\n'"$TLSSET_MAIN_PID"$'\n'* ]]
  else
    [ -n "$(_tlsset_processes)" ]
  fi
}

# _tlsset_new_process: 0 when a process of the product (of the chosen instance, with TLSSET_MAIN_PID) runs that did
# not at _tlsset_note_processes.
_tlsset_new_process() {
  local pid
  while IFS= read -r pid; do
    [ -z "$pid" ] || [[ $'\n'"${TLSSET_OLD_PROCESSES:-}"$'\n' == *$'\n'"$pid"$'\n'* ]] || return 0
  done <<< "$(_tlsset_processes "$TLSSET_MAIN_PID")"
  return 1
}

# sb_tlsset_settled: how a reload or a start went, read from the product's own processes after
# _tlsset_note_processes, whatever the command returned: 0 once a process runs that did not before (the new
# generation), 1 when none runs. A server re-reads its configuration after the command has returned (Apache exits
# there on what its configuration test let through), and on a busy, swapping server that takes its time: it looks once
# a second, and after TLSSET_WAIT seconds (default 300) with the old processes still there and no new one it returns 0.
sb_tlsset_settled() {
  local waited=0
  while :; do
    _tlsset_running || return 1
    ! _tlsset_new_process || return 0
    [ "$waited" -lt "${TLSSET_WAIT:-300}" ] || return 0
    sleep 1
    waited=$((waited + 1))
  done
}

# _tlsset_note_processes: which of the product's processes (of the chosen instance, with TLSSET_MAIN_PID) run before
# a reload or start (TLSSET_OLD_PROCESSES), so the wait after it can tell a reload that is still handing over from one
# that is done.
_tlsset_note_processes() { TLSSET_OLD_PROCESSES="$(_tlsset_processes "$TLSSET_MAIN_PID")"; }

# _tlsset_old_processes_left: how many of TLSSET_OLD_PROCESSES still run; one that exited and waits for its parent
# to collect it (state Z) has left.
_tlsset_old_processes_left() {
  local pid stat left=0
  while IFS= read -r pid; do
    [ -n "$pid" ] && stat="$(cat "/proc/$pid/stat" 2>/dev/null)" || continue
    stat="${stat##*) }"
    [ "${stat%% *}" = Z ] || left=$((left + 1))
  done <<< "${TLSSET_OLD_PROCESSES:-}"
  echo "$left"
}

# _tlsset_wait_for_listener: 0 when the local handshake answers and, when TLSSET_EXPECT_GROUP is set, agrees on that
# group. A reload hands the listener to new processes while the old ones finish, and a busy, swapping server takes
# its time, so it waits as long as that moves: each process of the old generation that leaves starts the count again.
# 1 when VERIFY_WAIT_SECONDS (default 300) have passed with neither the answer nor an old process leaving, or at once
# when the listener does not answer and the service is gone. A listener that did not answer before has nothing to
# wait for but the reload itself: 1 once the product's processes show how that went (sb_tlsset_settled), so a server
# that dies of the reload is seen where no handshake could show it.
_tlsset_wait_for_listener() {
  local still=0 left before
  before="$(_tlsset_old_processes_left)"
  while :; do
    sb_tlsset_probe
    if [ "$TLSSET_PROBE_OK" = true ]; then
      [ -n "$TLSSET_EXPECT_GROUP" ] && [ "$TLSSET_PROBE_GROUP" != "$TLSSET_EXPECT_GROUP" ] || return 0
    elif ! tlsset_alive || { [ "$TLSSET_RAN_BEFORE" = true ] && ! _tlsset_running; }; then
      return 1
    elif [ "$TLSSET_BASELINE_OK" != true ]; then
      [ "$TLSSET_RAN_BEFORE" != true ] || sb_tlsset_settled || true
      return 1
    fi
    left="$(_tlsset_old_processes_left)"
    if [ "$left" -lt "$before" ]; then before="$left"; still=0; fi
    [ "$still" -lt "$TLSSET_WAIT" ] || return 1
    sleep 1
    still=$((still + 1))
  done
}

# sb_restore for tls-apply: sslbrain's place as it was before this run, and a reload when this run had reloaded.
# A list the product refused at reload can stop it (Apache exits on one its libssl refuses), so a reload that fails
# starts a service that answered or ran before; a running service is never started or restarted. 0 when the listener
# answers where it answered before and the product's processes run where they ran before. The group may differ from
# the one seen before: that one came from what the server ran, and a change of the customer's own not yet reloaded
# takes effect with the reload.
_tlsset_restore() {
  TLSSET_EXPECT_GROUP=""
  tlsset_put "$TLSSET_PREVIOUS" || return 1
  [ -n "$TLSSET_RELOADED" ] || return 0
  tlsset_configtest >&2 || return 1
  _tlsset_running || TLSSET_MAIN_PID=""   # a reload command that starts a stopped server gives it a new parent process
  _tlsset_note_processes
  if tlsset_reload >&2; then
    TLSSET_RELOADS=$((TLSSET_RELOADS + 1))
  elif [ "$TLSSET_BASELINE_OK" = true ] || [ "$TLSSET_RAN_BEFORE" = true ]; then
    TLSSET_MAIN_PID=""   # a started service has a new parent process
    _tlsset_note_processes
    tlsset_start >&2 || return 1
    sb_event warning service_started "$TLSSET_PRODUCT was not running after the previous settings were put back, and was started"
  fi
  # Without a chosen parent the old processes answer the handshake until the reload has started new ones, which a
  # slow server does late: the handshake is asked once new ones run (sb_tlsset_settled), so it is theirs.
  [ "$TLSSET_RAN_BEFORE" != true ] || [ -n "$TLSSET_MAIN_PID" ] || sb_tlsset_settled || true
  # Back as before: answering where it answered before, or not answering where it did not before, and running: the
  # chosen parent, or, once it has gone, a process that did not run before (not another instance's) and the service.
  _tlsset_wait_for_listener || [ "$TLSSET_BASELINE_OK$TLSSET_PROBE_OK" = falsefalse ] || return 1
  [ "$TLSSET_RAN_BEFORE" != true ] || { tlsset_alive && _tlsset_running && { [ -n "$TLSSET_MAIN_PID" ] || _tlsset_new_process; }; } \
    || return 1
  [ "$TLSSET_PROBE_OK" != true ] || [ "$TLSSET_PROBE_GROUP" = "$TLSSET_GROUP_BEFORE" ] \
    || sb_event warning restored_group_differs "with the previous settings back the local handshake agrees on ${TLSSET_PROBE_GROUP:-no group}, before this run on ${TLSSET_GROUP_BEFORE:-no group}: the server's configuration had changed since its last reload"
}

# sb_tlsset_own_file_current and sb_tlsset_own_file_put FILE: sslbrain's place as one file of its own,
# TLSSET_TARGET; an empty FILE removes it.
sb_tlsset_own_file_current() { [ ! -e "$TLSSET_TARGET" ] || cat -- "$TLSSET_TARGET"; }

sb_tlsset_own_file_put() {
  if [ ! -s "$1" ]; then
    [ ! -e "$TLSSET_TARGET" ] || rm -f -- "$TLSSET_TARGET"
    return
  fi
  install -m 0644 -- "$1" "$TLSSET_TARGET"
}

# Each product's functions are defined when its turn comes, in a shell of its own: the three agents give their
# hooks the same names.
load_nginx() {
# From the sslbrain agents' v4/agents/nginx-ssh/nginx.sh:
# master_trusted /proc/PID: 0 when that process may choose the configuration this agent tests and reloads: it is
# root's or this account's, and it runs on this file system. A process title is whatever its owner writes, and nginx -t
# opens the files and loads the modules its configuration names; a container's master names paths that are other
# files here. The root of another account's process cannot be read without root, and is then taken as this one.
master_trusted() {
  local key real effective rest root comm=""
  # The program's own name, which a process title does not change: a setuid program that keeps its caller's title
  # is not nginx.
  read -r comm 2>/dev/null < "$1/comm" || true
  [ "$comm" = nginx ] || return 1
  while read -r key real effective rest; do [ "$key" != Uid: ] || break; done 2>/dev/null < "$1/status" || return 1
  [ "$key" = Uid: ] && [ "$real" = "$effective" ] || return 1
  [ "$real" = 0 ] || [ "$real" = "$(id -u)" ] || return 1
  # Root reads every process's root; a failure there is a process that has gone.
  root="$(stat -Lc %d:%i -- "$1/root" 2>/dev/null)" || [ "$(id -u)" != 0 ] || return 1
  [ -n "$root" ] || return 0
  [ "$root" = "$(stat -Lc %d:%i /)" ]
}

# nginx_find: NGINX (the binary, or empty), CONF_ARGS (-c/-p of the running master, see master_trusted), MASTER_PID
# (that master, or empty) and MAIN_CONF.
nginx_find() {
  local candidate proc title word next="" words
  NGINX="$(command -v nginx 2>/dev/null || true)"
  for candidate in /usr/sbin/nginx /usr/local/sbin/nginx /usr/local/nginx/sbin/nginx; do
    [ -n "$NGINX" ] || { [ -x "$candidate" ] && NGINX="$candidate"; } || true
  done
  CONF_ARGS=()
  MAIN_CONF=""
  MASTER_PID=""
  for proc in /proc/[0-9]*/cmdline; do
    title="$(tr '\0' ' ' 2>/dev/null < "$proc" || true)"
    case "$title" in "nginx: master process "*) ;; *) continue ;; esac
    master_trusted "${proc%/cmdline}" || continue
    MASTER_PID="${proc#/proc/}"; MASTER_PID="${MASTER_PID%/cmdline}"
    read -r -a words <<< "${title#nginx: master process }"
    for word in "${words[@]}"; do
      case "$next" in
        -c) MAIN_CONF="$word"; CONF_ARGS+=(-c "$word") ;;
        -p) CONF_ARGS+=(-p "$word") ;;
      esac
      next="$word"
    done
    break
  done
  if [ -z "$MAIN_CONF" ] && [ -n "$NGINX" ]; then
    MAIN_CONF="$("$NGINX" -V 2>&1 | tr ' ' '\n' | sed -n 's/^--conf-path=//p' | sed -n 1p)"
  fi
  case "$MAIN_CONF" in /*) ;; *) MAIN_CONF=/etc/nginx/nginx.conf ;; esac
}

# conf_expand FILE [DEPTH]: the configuration with every include expanded where it stands, each file announced by
# a line "#sslbrain-file <path>" and closed by "#sslbrain-end"; an unreadable file is "#sslbrain-unreadable <path>".
# Include patterns are globbed with compgen (pathnames only, nothing evaluated), relative to the main file's
# directory, sorted as nginx sorts them.
conf_expand() {
  local file="$1" depth="${2:-0}" line pattern match include_re='^[[:space:]]*include[[:space:]]+([^;]+);'
  [ "$depth" -le 16 ] || return 0
  if [ ! -r "$file" ]; then printf '#sslbrain-unreadable %s\n' "$file"; return 0; fi
  printf '#sslbrain-file %s\n' "$file"
  while IFS= read -r line || [ -n "$line" ]; do
    if [[ "$line" =~ $include_re ]]; then
      read -r pattern <<< "${BASH_REMATCH[1]//[\"\']/}"
      case "$pattern" in /*) ;; *) pattern="$(dirname -- "$MAIN_CONF")/$pattern" ;; esac
      while IFS= read -r match; do
        [ -f "$match" ] && conf_expand "$match" $((depth + 1))
      done < <(compgen -G "$pattern" | sort)
      printf '#sslbrain-back %s\n' "$file"
    else
      # A line of the file that looks like a marker is not one.
      case "$line" in "#sslbrain-"*) line="# $line" ;; esac
      printf '%s\n' "$line"
    fi
  done < "$file"
}

# conf_read: CONF (the expanded configuration), CONF_FILES (one loaded file per line, as its include names it),
# CONF_UNREADABLE (count).
conf_read() {
  CONF="$(conf_expand "$MAIN_CONF")"
  CONF_FILES="$(printf '%s\n' "$CONF" | sed -n 's/^#sslbrain-file //p' | awk '!seen[$0]++')"
  CONF_UNREADABLE="$(printf '%s\n' "$CONF" | grep -c '^#sslbrain-unreadable ' || true)"
}

# conf_mask: stdin with { } ; # and blanks inside a quoted string replaced by _, so a brace in
# `location ~ "^/x{2}"` or `return 200 "}"` neither opens a block nor ends a directive.
conf_mask() {
  awk '{ out = ""; q = ""
    for (i = 1; i <= length($0); i++) { c = substr($0, i, 1)
      if (q == "") { if (c == "\"" || c == "\047") q = c } else if (c == q) q = ""; else if (c ~ /[{};# \t]/) c = "_"
      out = out c }
    print out }'
}

# conf_servers: one line per certificate of a TLS server block of CONF, fields separated by US (\037, so an empty
# one stays): server names (space separated), port, ssl_certificate, ssl_certificate_key, the file the block starts
# in, and how many certificates the block has. A block has one, or one per key type (an RSA and an ECDSA one), each
# ssl_certificate with the ssl_certificate_key of the same position. A relative path is made absolute against the
# main file's directory, as nginx does.
# abs(v) is that normaliser, the same in each awk that compares a path with one discover reports (the command check
# takes no awk program built from a variable): a variable, a data: value and an absolute path stay as they are.
conf_servers() {
  printf '%s\n' "$CONF" | conf_mask | awk -v base="$(dirname -- "$MAIN_CONF")" '
    function unq(v) { gsub(/^["\047]|["\047]$/, "", v); return v }
    function abs(v) { return (v == "" || v ~ /^\// || v ~ /^\$/ || v ~ /^data:/) ? v : base "/" v }
    function port_of(v,   p) {
      if (v ~ /^unix:/) return ""
      p = v; sub(/^.*\]/, "", p); if (p ~ /:/) sub(/^.*:/, "", p)
      return (p ~ /^[0-9]+$/) ? p : (v ~ /^[0-9]+$/ ? v : "443")
    }
    /^#sslbrain-(file|back) / { file = substr($0, index($0, " ") + 1); next }
    /^#sslbrain-/ { next }
    {
      line = $0; sub(/#.*/, "", line); gsub(/[{};]/, " & ", line)
      n = split(line, w, /[ \t]+/)
      for (i = 1; i <= n; i++) {
        t = w[i]; if (t == "") continue
        if (t == "{") {
          depth++; ctx[depth] = word[1]
          if (word[1] == "server" && (ctx[depth - 1] == "http" || ctx[depth - 1] == "stream") && !sdepth) {
            sdepth = depth; names = ""; port = ""; anyport = ""; ncert = 0; nkey = 0; sfile = file
          }
          nw = 0; continue
        }
        if (t == "}") {
          if (depth == sdepth) {
            for (j = 1; j <= ncert; j++) print names "\037" (port != "" ? port : (anyport != "" ? anyport : "443")) "\037" abs(certs[j]) "\037" abs(j <= nkey ? keys[j] : "") "\037" sfile "\037" ncert
            sdepth = 0
          }
          depth--; nw = 0; continue
        }
        if (t == ";") {
          if (sdepth && depth == sdepth) {
            if (word[1] == "server_name") { for (j = 2; j <= nw; j++) names = names (names == "" ? "" : " ") unq(word[j]) }
            else if (word[1] == "listen") {
              ssl = 0; for (j = 3; j <= nw; j++) if (word[j] == "ssl") ssl = 1
              if (ssl && port == "") port = port_of(word[2])
              if (anyport == "") anyport = port_of(word[2])
            }
            else if (word[1] == "ssl_certificate") certs[++ncert] = unq(word[2])
            else if (word[1] == "ssl_certificate_key") keys[++nkey] = unq(word[2])
          }
          nw = 0; continue
        }
        word[++nw] = t
      }
    }'
}

# ${a[@]+...}: an empty array under set -u is an error before bash 4.4 (RHEL 7).
nginx_test() { "$NGINX" ${CONF_ARGS[@]+"${CONF_ARGS[@]}"} -t; }

nginx_reload() { "$NGINX" ${CONF_ARGS[@]+"${CONF_ARGS[@]}"} -s reload; }

TLS_CONF_COMMAND=false

# nginx_includes_tls_dir FILE...: 0 when one of the files includes the *.conf of the directory TLSSET_TARGET is in,
# written as conf.d/*.conf (nginx reads it beside the main file) or as that absolute path, quoted or not. awk reads
# the files itself, so a match early in a large file is a match, and it is plain POSIX awk, as busybox's is.
nginx_includes_tls_dir() {
  awk -v relative="conf.d/*.conf" -v absolute="$(dirname -- "$TLSSET_TARGET")/*.conf" '
    $1 == "include" {
      value = $0
      sub(/^[ \t]*include[ \t]+/, "", value)
      sub(/[ \t]*;.*$/, "", value)
      if (value ~ /^".*"$/) value = substr(value, 2, length(value) - 2)
      if (value == relative || value == absolute) { found = 1; exit }
    }
    END { exit !found }' "$@" 2>/dev/null
}

# nginx_at_least VERSION: 0 when TLSSET_VERSION is VERSION or newer.
nginx_at_least() {
  local -a have want
  local i
  IFS=. read -r -a have <<< "$TLSSET_VERSION"
  IFS=. read -r -a want <<< "$1"
  for i in 0 1 2; do
    [[ "${have[i]:-0}" =~ ^[0-9]+$ ]] || return 1
    (( 10#${have[i]:-0} > 10#${want[i]:-0} )) && return 0
    (( 10#${have[i]:-0} < 10#${want[i]:-0} )) && return 1
  done
  return 0
}

tlsset_detect() {
  local info
  local -a files
  TLSSET_PRODUCT=nginx
  TLSSET_PROCESS_NAMES=nginx
  nginx_find
  if [ -z "$NGINX" ]; then
    TLSSET_FAIL_CODE=not_installed; TLSSET_FAIL_MESSAGE="nginx was not found on this server"; return 1
  fi
  info="$("$NGINX" -V 2>&1 </dev/null || true)"
  TLSSET_VERSION=""
  [[ ! "$info" =~ nginx/([0-9][0-9.]*) ]] || TLSSET_VERSION="${BASH_REMATCH[1]}"
  TLSSET_LIBRARY=""
  if [[ "$info" =~ running\ with\ (OpenSSL\ [0-9][0-9.]*[a-z]*) ]] || [[ "$info" =~ built\ with\ (OpenSSL\ [0-9][0-9.]*[a-z]*) ]] \
     || [[ "$info" =~ built\ with\ ([A-Za-z-]+\ [0-9][0-9.]*) ]]; then
    TLSSET_LIBRARY="${BASH_REMATCH[1]}"
  fi
  TLSSET_TARGET="$(dirname -- "$MAIN_CONF")/conf.d/sslbrain-tls.conf"
  TLS_CONF_COMMAND=false
  ! nginx_at_least 1.19.4 || TLS_CONF_COMMAND=true
  conf_read
  # The last Groups or ssl_ecdh_curve the configuration sets; awk reads it all.
  TLSSET_GROUPS="$(awk '
    $1 == "ssl_conf_command" && $2 == "Groups" { g = $3 }
    $1 == "ssl_ecdh_curve" { g = $2 }
    END { sub(/;.*/, "", g); print g }' <<< "$CONF")"
  if [ "$CONF_UNREADABLE" != 0 ]; then
    TLSSET_FAIL_CODE=configuration_unreadable
    TLSSET_FAIL_MESSAGE="this account cannot read all of nginx's configuration; reading and writing it needs a root login, sudo elevation on the credential, or the sslbrain service agent"
    return 1
  fi
  mapfile -t files <<< "$CONF_FILES"
  if ! nginx_includes_tls_dir "${files[@]}"; then
    TLSSET_FAIL_CODE=not_supported
    TLSSET_FAIL_MESSAGE="nginx's configuration has no include of conf.d/*.conf ($(dirname -- "$TLSSET_TARGET")/*.conf); sslbrain writes its TLS settings only to $TLSSET_TARGET"
    return 1
  fi
  if [ ! -d "$(dirname -- "$TLSSET_TARGET")" ]; then
    TLSSET_FAIL_CODE=not_supported; TLSSET_FAIL_MESSAGE="$(dirname -- "$TLSSET_TARGET") does not exist"; return 1
  fi
}

tlsset_current() { sb_tlsset_own_file_current; }

tlsset_put() { sb_tlsset_own_file_put "$1"; }

tlsset_configtest() { nginx_test </dev/null; }

tlsset_reload() { nginx_reload </dev/null; }

tlsset_render() {
  [ "$TLSSET_WANT_PROFILE" = true ] || [ -n "$TLSSET_WANT_MIN_PROTOCOL" ] || [ -n "$TLSSET_WANT_GROUPS" ] || return 0
  printf '# sslbrain TLS settings. sslbrain writes and removes this file;\n'
  printf "# change the setting on the server's page in sslbrain, not here.\n"
  if [ "$TLS_CONF_COMMAND" = true ]; then
    [ -z "$TLSSET_WANT_MIN_PROTOCOL" ] || printf 'ssl_conf_command MinProtocol %s;\n' "$TLSSET_WANT_MIN_PROTOCOL"
    [ "$TLSSET_WANT_PROFILE" != true ] || printf 'ssl_conf_command CipherString %s;\n' "$TLS_CIPHERS"
    [ -z "$TLSSET_WANT_GROUPS" ] || printf 'ssl_conf_command Groups %s;\n' "$TLSSET_WANT_GROUPS"
  else
    [ "$TLSSET_WANT_PROFILE" != true ] || printf 'ssl_ciphers %s;\n' "$TLS_CIPHERS"
    [ -z "$TLSSET_WANT_GROUPS" ] || printf 'ssl_ecdh_curve %s;\n' "$TLSSET_WANT_GROUPS"
  fi
}

# A server block with its own ssl_conf_command does not inherit sslbrain's; before 1.19.4 its own ssl_ciphers or
# ssl_ecdh_curve wins. Line numbers per file from the expanded configuration: an include line is followed by the
# included files and a #sslbrain-back marker.
tlsset_conflicts() {
  local pattern=ssl_conf_command
  [ "$TLS_CONF_COMMAND" = true ] || pattern='ssl_ciphers|ssl_ecdh_curve'
  awk -v own="$TLSSET_TARGET" -v pattern="$pattern" '
    /^#sslbrain-file / { file = substr($0, 16); line[file] = 0; next }
    /^#sslbrain-back / { file = substr($0, 16); line[file]++; next }
    /^#sslbrain-/ { next }
    { line[file]++ }
    file != own && $1 ~ "^(" pattern ")$" { print file ":" line[file] " " $1 }' <<< "$CONF"
}

tlsset_prepare() {
  if [ "$TLS_CONF_COMMAND" != true ] && [ "$TLS_PROFILE" = sslbrain_recommended ]; then
    _tlsset_warn protocols_unchanged "nginx $TLSSET_VERSION has no ssl_conf_command (added in nginx 1.19.4); the protocols stay as nginx.conf sets them"
  fi
}
}

load_apache() {
# From the sslbrain agents' v4/lib/bash/apache.sh:
# sb_apache_find: sets SB_APACHE_CTL (apache2ctl, apachectl or httpd), SB_APACHE_READ: the program that takes
# arguments (httpd beside an apachectl that refuses -S, else SB_APACHE_CTL), SB_APACHE_ARGS: the -d/-f the running
# Apache was started with when they are not the compiled default, else empty, and SB_APACHE_PID: that Apache's parent
# process, empty when none runs. Only a root-owned apache2/httpd parent process answers, so another account's process
# with that name chooses nothing. Returns 1 when Apache is not installed.
sb_apache_find() {
  PATH="${PATH:-/usr/bin:/bin}:/usr/local/sbin:/usr/sbin:/sbin"   # a non-root login's PATH lacks the sbin directories
  SB_APACHE_CTL=""
  SB_APACHE_READ=""
  SB_APACHE_ARGS=()
  SB_APACHE_PID=""
  local name pid parent arg want=""
  for name in apache2ctl apachectl httpd; do
    SB_APACHE_CTL="$(command -v "$name" 2>/dev/null || true)"
    [ -z "$SB_APACHE_CTL" ] || break
  done
  [ -n "$SB_APACHE_CTL" ] || return 1
  # Red Hat's apachectl on RHEL 9 refuses -S, -M and -t -D: httpd answers them there. Where apachectl takes -S (RHEL
  # 7 and 8, which pass the options of /etc/sysconfig/httpd on), and for Debian's apache2ctl, nothing changes.
  SB_APACHE_READ="$SB_APACHE_CTL"
  if [ "${SB_APACHE_CTL##*/}" = apachectl ] && command -v httpd >/dev/null 2>&1 \
     && ! "$SB_APACHE_CTL" -S >/dev/null 2>&1 </dev/null 3>&-; then
    SB_APACHE_READ="$(command -v httpd)"
  fi
  for pid in $(grep -lxE 'apache2|httpd' /proc/[0-9]*/comm 2>/dev/null | cut -d/ -f3); do
    parent="$(awk '$1 == "PPid:" { print $2 }' "/proc/$pid/status" 2>/dev/null || true)"
    grep -qxE 'apache2|httpd' "/proc/$parent/comm" 2>/dev/null && continue
    awk '$1 == "Uid:" { exit !($2 == 0 && $3 == 0) }' "/proc/$pid/status" 2>/dev/null || continue
    SB_APACHE_PID="$pid"
    while IFS= read -r arg; do
      if [ -n "$want" ]; then
        [[ "$arg" =~ ^/[A-Za-z0-9_./@+,=~-]+$ ]] && SB_APACHE_ARGS+=("$want" "$arg")
        want=""
      elif [ "$arg" = -d ] || [ "$arg" = -f ]; then
        want="$arg"
      fi
    done < <(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null)
    break
  done
}

# sb_apache_ctl ARG...: SB_APACHE_READ on the running configuration (-v, -S, -M, -t -D DUMP_INCLUDES, -k with
# -d/-f). Fd 3 is closed for it: over ssh it carries the result, and an Apache that graceful starts would otherwise
# hold the channel open for as long as it runs.
sb_apache_ctl() { "$SB_APACHE_READ" ${SB_APACHE_ARGS[@]+"${SB_APACHE_ARGS[@]}"} "$@" </dev/null 3>&-; }

# sb_apache_configtest and sb_apache_graceful: the configuration test and the graceful restart (which starts Apache
# when it is not running). Without -d/-f these are the plain `apachectl configtest` and `apachectl graceful`.
sb_apache_configtest() {
  if [ ${#SB_APACHE_ARGS[@]} -gt 0 ]; then sb_apache_ctl -t; else "$SB_APACHE_CTL" configtest </dev/null 3>&-; fi
}

sb_apache_graceful() {
  if [ ${#SB_APACHE_ARGS[@]} -gt 0 ]; then sb_apache_ctl -k graceful; else "$SB_APACHE_CTL" graceful </dev/null 3>&-; fi
}

# sb_apache_unit: SB_APACHE_UNIT, the systemd unit that runs Apache (apache2 on Debian, httpd on RHEL), or empty; found
# before anything changes. Debian's apache2ctl graceful signals Apache directly and starts a stopped one outside its
# unit, which systemd then reports failed while the site answers, and RHEL's apachectl graceful does not start a
# stopped httpd: a stopped Apache is started through its unit (sb_apache_start).
sb_apache_unit() {
  local unit
  SB_APACHE_UNIT=""
  [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1 || return 0
  for unit in apache2 httpd; do
    if systemctl is-active --quiet "$unit" 2>/dev/null; then SB_APACHE_UNIT="$unit"; return 0; fi
  done
}

# sb_apache_start: starts a stopped Apache, through its unit when one ran it.
sb_apache_start() {
  if [ -n "${SB_APACHE_UNIT:-}" ]; then systemctl start "$SB_APACHE_UNIT" </dev/null 3>&-; else sb_apache_ctl -k start; fi
}

# sb_apache_path VALUE: a file name from the configuration as an absolute path without symlinks; relative to
# ServerRoot. Prints nothing for a value with a variable (${...}) or a pkcs11: reference.
sb_apache_path() {
  local value="${1#\"}"
  value="${value%\"}"
  case "$value" in ''|*'$'*|pkcs11:*) return 0 ;; /*) ;; *) value="$SB_APACHE_ROOT/$value" ;; esac
  realpath -m -- "$value"
}

# sb_apache_vhosts: the VirtualHosts of the loaded configuration (-S), each once, in the arrays
# SB_VH_NAME (ServerName), SB_VH_NAMES (ServerName and aliases, space-separated), SB_VH_HOST and SB_VH_PORT (its
# first address), SB_VH_TLS (true when SSLEngine is on or it names a certificate), SB_VH_CERTS and SB_VH_KEYS (the
# certificate and key files, one per line, pairs by line), SB_VH_CHAIN; and SB_APACHE_ROOT, SB_APACHE_PIDFILE.
# Returns 1 when -S fails.
sb_apache_vhosts() {
  SB_VH_NAME=(); SB_VH_NAMES=(); SB_VH_HOST=(); SB_VH_PORT=(); SB_VH_TLS=(); SB_VH_CERTS=(); SB_VH_KEYS=(); SB_VH_CHAIN=()
  local dump location file line i directive value address
  local -a words
  dump="$(sb_apache_ctl -S 2>&1)" || return 1
  SB_APACHE_ROOT="$(printf '%s\n' "$dump" | sed -n 's/^ServerRoot: "\(.*\)"$/\1/p' | sed -n 1p)"
  SB_APACHE_PIDFILE="$(printf '%s\n' "$dump" | sed -n 's/^PidFile: "\(.*\)"$/\1/p' | sed -n 1p)"
  [ -z "$SB_APACHE_PIDFILE" ] || SB_APACHE_PIDFILE="$(sb_apache_path "$SB_APACHE_PIDFILE")"
  while IFS= read -r location; do
    file="${location%:*}"
    line="${location##*:}"
    i=${#SB_VH_NAME[@]}
    SB_VH_NAME[i]=""; SB_VH_NAMES[i]=""; SB_VH_HOST[i]=""; SB_VH_PORT[i]=443; SB_VH_TLS[i]=false
    SB_VH_CERTS[i]=""; SB_VH_KEYS[i]=""; SB_VH_CHAIN[i]=""
    while IFS=$'\t' read -r directive value; do
      case "$directive" in
        '<virtualhost')
          address="${value%%[[:space:]]*}"
          address="${address%>}"
          case "$address" in *:[0-9]*) SB_VH_PORT[i]="${address##*:}"; address="${address%:*}" ;; esac
          SB_VH_HOST[i]="${address#[}"; SB_VH_HOST[i]="${SB_VH_HOST[i]%]}" ;;
        servername)
          value="${value#*://}"; SB_VH_NAME[i]="${value%%:*}"; SB_VH_NAMES[i]="${SB_VH_NAME[i]} ${SB_VH_NAMES[i]}" ;;
        serveralias) SB_VH_NAMES[i]="${SB_VH_NAMES[i]} $value" ;;
        sslengine) [ "${value,,}" != on ] || SB_VH_TLS[i]=true ;;
        sslcertificatefile) SB_VH_CERTS[i]+="$(sb_apache_path "$value")"$'\n'; SB_VH_TLS[i]=true ;;
        sslcertificatekeyfile) SB_VH_KEYS[i]+="$(sb_apache_path "$value")"$'\n' ;;
        sslcertificatechainfile) SB_VH_CHAIN[i]="$(sb_apache_path "$value")" ;;
      esac
    done < <(awk -v start="$line" 'NR < start { next }
      { sub(/^[ \t]+/, ""); sub(/[ \t\r]+$/, ""); d = tolower($1) }
      NR > start && d ~ /^<\/virtualhost/ { exit }
      d ~ /^(<virtualhost|servername|serveralias|sslengine|sslcertificatefile|sslcertificatekeyfile|sslcertificatechainfile)$/ {
        v = $0; sub(/^[^ \t]+[ \t]*/, "", v); print d "\t" v }' "$file" 2>/dev/null)
    read -r -a words <<< "${SB_VH_NAMES[i]}"
    SB_VH_NAMES[i]="$(printf '%s\n' ${words[@]+"${words[@]}"} | awk '!seen[$0]++' | tr '\n' ' ')"
    SB_VH_NAMES[i]="${SB_VH_NAMES[i]% }"
  done < <(printf '%s\n' "$dump" | sed -n 's/.*(\(\/[^()]*:[0-9][0-9]*\))[[:space:]]*$/\1/p' | awk '!seen[$0]++')
}

SB_APACHE_UNIT=""

tlsset_detect() {
  local info main
  TLSSET_PRODUCT="Apache httpd"
  TLSSET_PROCESS_NAMES="apache2 httpd"
  if ! sb_apache_find; then
    TLSSET_FAIL_CODE=not_installed; TLSSET_FAIL_MESSAGE="apache2ctl, apachectl or httpd was not found on this server"; return 1
  fi
  TLSSET_MAIN_PID="$SB_APACHE_PID"   # a graceful restart keeps the parent process
  info="$(sb_apache_ctl -v 2>/dev/null || true)"
  TLSSET_VERSION=""
  [[ ! "$info" =~ Apache/([0-9][0-9.]*) ]] || TLSSET_VERSION="${BASH_REMATCH[1]}"
  # mod_ssl links the system's libssl on Debian, Ubuntu and RHEL, which the system's own openssl reports; an openssl
  # earlier in PATH (a self-built one in /usr/local/bin) says nothing about what Apache loads.
  if [ -x /usr/bin/openssl ]; then info="$(/usr/bin/openssl version 2>/dev/null || true)"; else info="$(openssl version 2>/dev/null || true)"; fi
  TLSSET_LIBRARY=""
  [[ ! "$info" =~ ^(OpenSSL\ [0-9][0-9.]*[a-z]*) ]] || TLSSET_LIBRARY="${BASH_REMATCH[1]}"
  if [ -d /etc/apache2/conf-enabled ]; then
    TLSSET_TARGET=/etc/apache2/conf-enabled/sslbrain-tls.conf; main=/etc/apache2/apache2.conf
  elif [ -d /etc/httpd/conf.d ]; then
    TLSSET_TARGET=/etc/httpd/conf.d/sslbrain-tls.conf; main=/etc/httpd/conf/httpd.conf
  else
    TLSSET_FAIL_CODE=not_supported
    TLSSET_FAIL_MESSAGE="neither /etc/apache2/conf-enabled nor /etc/httpd/conf.d exists; sslbrain writes its TLS settings only there"
    return 1
  fi
  TLSSET_GROUPS=""
  [ ! -r "$TLSSET_TARGET" ] || TLSSET_GROUPS="$(awk 'tolower($1) == "sslopensslconfcmd" && $2 == "Groups" { g = $3 } END { print g }' "$TLSSET_TARGET")"
  # grep reads the file itself: a match early in a large file is a match.
  if ! grep -Eqi '^[[:space:]]*Include(Optional)?[[:space:]]+"?([^[:space:]"]*/)?(conf-enabled|conf\.d)/\*(\.conf)?"?[[:space:]]*$' "$main" 2>/dev/null; then
    TLSSET_FAIL_CODE=not_supported
    TLSSET_FAIL_MESSAGE="$main does not include $(dirname -- "$TLSSET_TARGET"); sslbrain writes its TLS settings only to $TLSSET_TARGET"
    return 1
  fi
  if [[ "$(sb_apache_ctl -M 2>/dev/null || true)" != *ssl_module* ]]; then
    TLSSET_FAIL_CODE=not_supported; TLSSET_FAIL_MESSAGE="mod_ssl is not loaded, so Apache serves no TLS to set"; return 1
  fi
  sb_apache_unit
}

tlsset_current() { sb_tlsset_own_file_current; }

tlsset_put() { sb_tlsset_own_file_put "$1"; }

tlsset_render() {
  [ "$TLSSET_WANT_PROFILE" = true ] || [ -n "$TLSSET_WANT_MIN_PROTOCOL" ] || [ -n "$TLSSET_WANT_GROUPS" ] || return 0
  printf '# sslbrain TLS settings. sslbrain writes and removes this file;\n'
  printf "# change the setting on the server's page in sslbrain, not here.\n"
  printf '<IfModule ssl_module>\n'
  case "$TLSSET_WANT_MIN_PROTOCOL" in
    TLSv1.3) printf '    SSLProtocol -all +TLSv1.3\n' ;;
    TLSv1.2) printf '    SSLProtocol -all +TLSv1.2 +TLSv1.3\n' ;;
  esac
  if [ "$TLSSET_WANT_PROFILE" = true ]; then
    printf '    SSLCipherSuite %s\n' "$TLS_CIPHERS"
    printf '    SSLHonorCipherOrder off\n'
  fi
  [ -z "$TLSSET_WANT_GROUPS" ] || printf '    SSLOpenSSLConfCmd Groups %s\n' "$TLSSET_WANT_GROUPS"
  printf '</IfModule>\n'
}

# The configuration test does not load the cipher list, so a list Apache's OpenSSL cannot use is first refused by the
# reload itself; the restore then starts the unit again.
tlsset_configtest() { sb_apache_configtest; }

tlsset_reload() {
  if [ -n "$SB_APACHE_UNIT" ]; then systemctl reload "$SB_APACHE_UNIT" </dev/null 3>&-; else sb_apache_graceful; fi
}

tlsset_alive() { [ -z "$SB_APACHE_UNIT" ] || systemctl is-active --quiet "$SB_APACHE_UNIT" 2>/dev/null; }

tlsset_start() { sb_apache_start; }

# Every file Apache loads, and in each the TLS directives a <VirtualHost> sets for itself. -t -D DUMP_INCLUDES
# prints the files as a tree, each with the line of the Include that loaded it: "(225) /path" indented beneath the
# file that holds that line. A file an Include inside a <VirtualHost> loads belongs to that virtual host with all it
# includes (certbot's options-ssl-apache.conf is loaded so), so its TLS directives count as the virtual host's.
tlsset_conflicts() {
  local line indent at file found depth=0 started
  local -A included_inside=() read_as=()
  local -a tree_indent=() tree_file=() tree_inside=()
  while IFS= read -r line; do
    [[ "$line" =~ ^([[:space:]]*)\(([0-9*]+)\)[[:space:]]*(/.*)$ ]] || continue
    indent=${#BASH_REMATCH[1]}; at="${BASH_REMATCH[2]}"; file="${BASH_REMATCH[3]}"
    while [ "$depth" -gt 0 ] && [ "${tree_indent[depth-1]}" -ge "$indent" ]; do depth=$((depth - 1)); done
    started=0
    if [ "$depth" -gt 0 ]; then
      [ "${tree_inside[depth-1]}" != 1 ] && [ -z "${included_inside["${tree_file[depth-1]}:$at"]:-}" ] || started=1
    fi
    tree_indent[depth]="$indent"; tree_file[depth]="$file"; tree_inside[depth]="$started"
    depth=$((depth + 1))
    [ "$file" != "$TLSSET_TARGET" ] || continue
    [ -z "${read_as["$started:$file"]:-}" ] || continue
    read_as["$started:$file"]=1
    while IFS= read -r found; do
      if [[ "$found" == "include "* ]]; then included_inside["$file:${found#include }"]=1; else printf '%s\n' "$found"; fi
    done < <(awk -v file="$file" -v inside="$started" '
      { line++; d = tolower($1) }
      d ~ /^<virtualhost(>|$)/ { vhost = 1 }
      d ~ /^<\/virtualhost>/ { vhost = 0 }
      (inside || vhost) && (d == "sslprotocol" || d == "sslciphersuite") { print file ":" line " " $1 }
      (inside || vhost) && d == "sslopensslconfcmd" && ($2 == "Groups" || $2 == "Curves") { print file ":" line " SSLOpenSSLConfCmd Groups" }
      vhost && (d == "include" || d == "includeoptional") { print "include " line }' "$file" 2>/dev/null || true)
  done < <(sb_apache_ctl -t -D DUMP_INCLUDES 2>/dev/null) | awk '!seen[$0]++'
}
}

load_haproxy() {
SERVICE=""
# From the sslbrain agents' v4/agents/haproxy-ssh/haproxy.sh:
DEFAULT_CONFIG=/etc/haproxy/haproxy.cfg

US=$'\037'

HOST_RE='^([A-Za-z0-9][A-Za-z0-9.-]{0,252}|[0-9A-Fa-f]{0,4}:[0-9A-Fa-f:.]{1,40})$'

# haproxy_find: HAPROXY (the binary, or empty), MASTER_PID and MASTER_WORKER (the running master and whether it runs
# in master-worker mode, so SIGUSR2 reloads it), CONF_ARGS (the -f arguments the master runs with, or CONFIG_PATH)
# and MASTER_CWD (what a relative crt path is relative to). With several instances, the master the PID file names,
# else the one started with CONFIG_PATH, else the first. RAN_BEFORE is non-empty when that HAProxy ran at this point.
haproxy_find() {
  local proc pid pidfile="${SB_IN[HAPROXY_PID_FILE]:-}" given="${SB_IN[CONFIG_PATH]:-}"
  [ "$given" != "$DEFAULT_CONFIG" ] || given=""
  HAPROXY="$(command -v haproxy 2>/dev/null || true)"
  for pid in /usr/sbin/haproxy /usr/local/sbin/haproxy; do
    [ -n "$HAPROXY" ] || { [ -x "$pid" ] && HAPROXY="$pid"; } || true
  done
  MASTER_PID=""
  if [ -n "$pidfile" ] && [ -f "$pidfile" ]; then
    pid="$(head -n 1 -- "$pidfile" | tr -cd '0-9')"
    is_haproxy "$pid" && MASTER_PID="$pid"
  fi
  for proc in /proc/[0-9]*; do
    [ -z "$MASTER_PID" ] || break
    pid="${proc#/proc/}"
    is_haproxy "$pid" || continue
    is_haproxy "$(awk '$1 == "PPid:" { print $2 }' "$proc/status" 2>/dev/null || true)" && continue   # a worker
    master_args "$pid"
    [ -z "$given" ] || grep -qxF -- "$given" <<< "$(printf '%s\n' ${CONF_ARGS[@]+"${CONF_ARGS[@]}"})" || continue
    MASTER_PID="$pid"
  done
  RAN_BEFORE="$MASTER_PID"
  master_args "$MASTER_PID"
  # The default stands for what the running HAProxy uses; any other path is used as given.
  if [ -n "$given" ]; then
    CONF_ARGS=("$given")
  elif [ "${#CONF_ARGS[@]}" -eq 0 ]; then
    CONF_ARGS=("$DEFAULT_CONFIG")
  fi
}

# master_args PID: CONF_ARGS (its -f arguments), MASTER_WORKER and MASTER_CWD of the haproxy PID (empty: none).
master_args() {
  local arg next=""
  CONF_ARGS=()
  MASTER_WORKER=""
  MASTER_CWD=/
  [ -n "$1" ] && [ -r "/proc/$1/cmdline" ] || return 0
  MASTER_CWD="$(readlink -- "/proc/$1/cwd" 2>/dev/null || echo /)"
  while IFS= read -r -d '' arg; do
    case "$arg" in -W|-Ws) MASTER_WORKER=1 ;; esac
    [ "$next" != -f ] || CONF_ARGS+=("$arg")
    next="$arg"
  done < "/proc/$1/cmdline"
}

# is_haproxy PID: 0 when PID is a running haproxy of root or of this account. Another account's process must not
# choose the configuration whose crt lines say which files this agent may write.
is_haproxy() {
  [ -n "$1" ] && [ -r "/proc/$1/cmdline" ] || return 1
  local name="" owner
  owner="$(stat -c %u -- "/proc/$1" 2>/dev/null || true)"
  [ "$owner" = 0 ] || [ "$owner" = "$(id -u)" ] || return 1
  IFS= read -r -d '' name < "/proc/$1/cmdline" || true
  [ "${name##*/}" = haproxy ]
}

# conf_read: CONF_FILES (one loaded file per line: a -f directory gives its *.cfg files in name order, as HAProxy
# loads them), CONF_LISTS (the crt-list files), CONF_UNREADABLE (count) and ENTRIES, one line per certificate file a TLS bind line loads, fields
# separated by US: frontend, port, certificate file, how it is named (crt, dir or crt-list), and the address the bind
# line names (empty for a wildcard, or one LOCAL_TLS_HOST would not take).
conf_read() {
  local arg file base kind f1 f2 host f3 raw path item
  CONF_FILES=""
  CONF_LISTS=""
  CONF_UNREADABLE=0
  for arg in "${CONF_ARGS[@]}"; do
    if [ -d "$arg" ]; then
      for file in "${arg%/}"/*.cfg; do [ -f "$file" ] && CONF_FILES+="$file"$'\n'; done
    elif [ -r "$arg" ]; then
      CONF_FILES+="$arg"$'\n'
    else
      CONF_UNREADABLE=$((CONF_UNREADABLE + 1))
    fi
  done
  ENTRIES=""
  base="$MASTER_CWD"
  while IFS="$US" read -r kind f1 f2 host f3 raw; do
    case "$kind" in
      base) base="$(abs_path "$f1" "$MASTER_CWD")"; continue ;;
    esac
    [[ "$host" =~ $HOST_RE ]] || host=""
    path="$(abs_path "$raw" "$base")"
    if [ "$f3" = crt-list ]; then
      [ -r "$path" ] || { CONF_UNREADABLE=$((CONF_UNREADABLE + 1)); continue; }
      CONF_LISTS+="$path"$'\n'
      while read -r item _ || [ -n "$item" ]; do
        case "$item" in ''|'#'*) continue ;; esac
        ENTRIES+="$f1$US$f2$US$(abs_path "$item" "$base")${US}crt-list$US$host"$'\n'
      done < "$path"
    elif [ -d "$path" ]; then
      for item in "${path%/}"/*; do
        [ -f "$item" ] || continue
        case "$item" in *.key|*.issuer|*.ocsp|*.sctl) continue ;; esac
        ENTRIES+="$f1$US$f2$US$item${US}dir$US$host"$'\n'
      done
    else
      ENTRIES+="$f1$US$f2$US$path${US}crt$US$host"$'\n'
    fi
  done < <(conf_binds)
}

# conf_binds: from the loaded files, a line "base<US><dir>" for crt-base and one line per crt or crt-list of a bind
# line with ssl: "bind<US><frontend><US><port><US><address><US><crt|crt-list><US><path>". The address is the first
# one the bind line names, without brackets, and empty for a wildcard (*, 0.0.0.0, ::) or none. Comments and quotes
# are stripped; no value is evaluated.
conf_binds() {
  local file
  while IFS= read -r file; do [ -n "$file" ] && cat -- "$file" && echo; done <<< "$CONF_FILES" | awk '
    function port_of(a,   p) {
      sub(/,.*$/, "", a)
      if (a ~ /^(unix|abns|fd|sockpair)@/ || a ~ /^\//) return ""
      p = a; sub(/^.*:/, "", p); sub(/-.*$/, "", p)
      return (p ~ /^[0-9]+$/) ? p : ""
    }
    function host_of(a,   h) {
      sub(/,.*$/, "", a); sub(/^ipv[46]@/, "", a)
      if (a ~ /@/ || a ~ /^\//) return ""
      h = ""
      if (a ~ /^\[/) { h = a; sub(/^\[/, "", h); sub(/\].*$/, "", h) }
      else if (a ~ /:/) { h = a; sub(/:[^:]*$/, "", h) }
      return (h == "*" || h == "0.0.0.0" || h == "::") ? "" : h
    }
    {
      line = $0; sub(/^[ \t]+/, "", line); if (line ~ /^#/) next; sub(/[ \t]+#.*$/, "", line)
      n = split(line, w, /[ \t]+/); if (n == 0 || w[1] == "") next
      for (i = 1; i <= n; i++) gsub(/^["\047]|["\047]$/, "", w[i])
      if (w[1] == "crt-base") { print "base\037" w[2] }
      else if (w[1] == "frontend" || w[1] == "listen") section = w[2]
      else if (w[1] ~ /^(global|defaults|backend|peers|resolvers|userlist|cache|program|http-errors|ring|mailers|crt-store)$/) section = ""
      else if (w[1] == "bind" && section != "") {
        ssl = 0; for (i = 3; i <= n; i++) if (w[i] == "ssl") ssl = 1
        if (!ssl) next
        for (i = 3; i < n; i++) if (w[i] == "crt" || w[i] == "crt-list") { print "bind\037" section "\037" port_of(w[2]) "\037" host_of(w[2]) "\037" w[i] "\037" w[i + 1] }
      }
    }'
}

# abs_path PATH BASE: PATH made absolute against BASE, with // and a trailing / removed.
abs_path() {
  local path="$1"
  case "$path" in /*) ;; *) path="${2%/}/$path" ;; esac
  path="$(printf '%s' "$path" | tr -s /)"
  [ "$path" = / ] || path="${path%/}"
  printf '%s' "$path"
}

haproxy_test() {
  local arg
  local -a args=(-c)
  for arg in "${CONF_ARGS[@]}"; do args+=(-f "$arg"); done
  "$HAPROXY" "${args[@]}"
}

# haproxy_reload: through systemd or the init script, else SIGUSR2 to a master-worker master (a container or a
# host without init). fd 3 closed, so nothing it starts holds the ssh result channel open.
haproxy_reload() {
  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ] || command -v service >/dev/null 2>&1; then
    sb_service_reload "$SERVICE" 3>&-
  elif [ -n "$MASTER_PID" ] && [ -n "$MASTER_WORKER" ]; then
    kill -USR2 "$MASTER_PID"
  else
    echo "no systemd, no service command and no HAProxy master in master-worker mode to signal" >&2
    return 1
  fi
}

# haproxy_runs: 0 while the HAProxy this run works on runs: its master, when it runs in master-worker mode (a reload
# keeps that process, and another instance on the host has processes of the same name); else any HAProxy process,
# because a reload without master-worker mode replaces the process, which then runs as the account the configuration's
# `user` names (haproxy). Whose process may choose the configuration is is_haproxy's question, not this one.
haproxy_runs() {
  local proc name
  if [ -n "$MASTER_PID" ] && [ -n "$MASTER_WORKER" ]; then
    name="$(cat "/proc/$MASTER_PID/stat" 2>/dev/null || true)"
    name="${name##*) }"
    [ -n "$name" ] && [ "${name%% *}" != Z ] && is_haproxy "$MASTER_PID"
    return
  fi
  for proc in /proc/[0-9]*; do
    { read -r name < "$proc/comm"; } 2>/dev/null || continue
    [ "$name" = haproxy ] || continue
    name=""
    IFS= read -r -d '' name < "$proc/cmdline" 2>/dev/null || true
    [ "${name##*/}" != haproxy ] || return 0
  done
  return 1
}

# haproxy_start: starts the service when no HAProxy runs; a running one is never started or restarted. Returns 1
# when one runs or the host has neither systemd nor a service command. fd 3 closed, as for the reload.
haproxy_start() {
  ! haproxy_runs || return 1
  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then systemctl start "$SERVICE" </dev/null 3>&- || return 1
  elif command -v service >/dev/null 2>&1; then service "$SERVICE" start </dev/null 3>&- || return 1
  else return 1; fi
  MASTER_PID=""   # the started HAProxy has a new master
}

# init_system: how this host reloads HAProxy.
init_system() {
  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then echo systemd
  elif command -v service >/dev/null 2>&1; then echo service
  elif [ -n "$MASTER_WORKER" ]; then echo master-worker
  else echo none; fi
}

TLS_BEGIN='# BEGIN sslbrain-tls'

TLS_END='# END sslbrain-tls'

tlsset_detect() {
  local info
  TLSSET_PRODUCT=HAProxy
  TLSSET_PROCESS_NAMES=haproxy
  haproxy_find
  [ -z "$MASTER_WORKER" ] || TLSSET_MAIN_PID="$MASTER_PID"   # a master-worker reload keeps the master process
  if [ -z "$HAPROXY" ]; then
    TLSSET_FAIL_CODE=not_installed; TLSSET_FAIL_MESSAGE="haproxy was not found on this server"; return 1
  fi
  info="$("$HAPROXY" -vv 2>&1 </dev/null || true)"
  TLSSET_VERSION=""
  [[ ! "$info" =~ HA-?Proxy\ version\ ([0-9][0-9.]*) ]] || TLSSET_VERSION="${BASH_REMATCH[1]}"
  TLSSET_LIBRARY=""
  if [[ "$info" =~ Running\ on\ OpenSSL\ version\ :\ (OpenSSL\ [0-9][0-9.]*[a-z]*) ]]; then
    TLSSET_LIBRARY="${BASH_REMATCH[1]}"
  elif [[ "$info" =~ Running\ on\ [A-Za-z-]+\ version\ :\ ([^$'\n']+) ]]; then
    TLSSET_LIBRARY="${BASH_REMATCH[1]}"
  fi
  if [ "${#CONF_ARGS[@]}" -ne 1 ] || [ -d "${CONF_ARGS[0]}" ]; then
    TLSSET_FAIL_CODE=not_supported
    TLSSET_FAIL_MESSAGE="HAProxy runs with several configuration files or a directory (${CONF_ARGS[*]}); sslbrain writes its TLS settings only into a single configuration file"
    return 1
  fi
  # The file itself, not a link to it: the rename below would replace a link into configuration management.
  TLSSET_TARGET="$(readlink -f -- "${CONF_ARGS[0]}")"
  if [ ! -r "$TLSSET_TARGET" ]; then
    TLSSET_FAIL_CODE=configuration_unreadable
    TLSSET_FAIL_MESSAGE="$TLSSET_TARGET cannot be read with this account; reading and writing it needs a root login, sudo elevation on the credential, or the sslbrain service agent"
    return 1
  fi
  TLSSET_GROUPS="$(awk '$1 == "ssl-default-bind-curves" { g = $2 } END { print g }' "$TLSSET_TARGET")"
  if [ -z "${SERVICE:-}" ] && [ "$(init_system)" = systemd ]; then
    SERVICE="$(systemctl list-units --type=service --state=running --no-legend 'haproxy*' 2>/dev/null \
      | awk '{ for (i = 1; i <= NF; i++) if ($i ~ /^haproxy.*\.service$/) { sub(/\.service$/, "", $i); print $i; exit } }' || true)"
  fi
  SERVICE="${SERVICE:-haproxy}"
  if [ "$(init_system)" = none ]; then
    TLSSET_FAIL_CODE=not_supported
    TLSSET_FAIL_MESSAGE="this host has no systemd or service command and HAProxy does not run in master-worker mode (-W), so it cannot be reloaded without a restart"
    return 1
  fi
}

tlsset_current() {
  awk -v begin="$TLS_BEGIN" -v end="$TLS_END" '
    index($0, begin) == 1 { inside = 1 }
    inside { print }
    inside && $0 == end { inside = 0 }' "$TLSSET_TARGET"
}

tlsset_render() {
  [ "$TLSSET_WANT_PROFILE" = true ] || [ -n "$TLSSET_WANT_MIN_PROTOCOL" ] || [ -n "$TLSSET_WANT_GROUPS" ] || return 0
  printf "%s: sslbrain writes and removes this section; change the setting on the server's page in sslbrain, not here.\n" "$TLS_BEGIN"
  printf 'global\n'
  [ -z "$TLSSET_WANT_MIN_PROTOCOL" ] || printf '    ssl-default-bind-options ssl-min-ver %s\n' "$TLSSET_WANT_MIN_PROTOCOL"
  [ "$TLSSET_WANT_PROFILE" != true ] || printf '    ssl-default-bind-ciphers %s\n' "$TLS_CIPHERS"
  [ -z "$TLSSET_WANT_GROUPS" ] || printf '    ssl-default-bind-curves %s\n' "$TLSSET_WANT_GROUPS"
  printf '%s\n' "$TLS_END"
}

# tlsset_put FILE: the configuration without sslbrain's section, with FILE's section (if any) before the first proxy
# section, through a copy beside it (cp -p, so it keeps the file's mode and owner, also with busybox) and a rename.
tlsset_put() {
  local next
  next="$(mktemp "$(dirname -- "$TLSSET_TARGET")/.sslbrain-tls.XXXXXX")" || return 1
  if cp -p -- "$TLSSET_TARGET" "$next" && awk -v begin="$TLS_BEGIN" -v end="$TLS_END" -v block="$1" '
       BEGIN { while ((getline line < block) > 0) { text = text line "\n" } }
       index($0, begin) == 1 { skip = 1 }
       skip { if ($0 == end) skip = 0; next }
       !placed && text != "" && $0 ~ /^(defaults|frontend|backend|listen|peers|resolvers|userlist|mailers|program|cache|http-errors|ring|log-forward|crt-store|fcgi-app|traces)([ \t]|$)/ {
         printf "%s", text; placed = 1
       }
       { print }
       END { if (!placed && text != "") printf "%s", text }' "$TLSSET_TARGET" > "$next" \
     && mv -f -- "$next" "$TLSSET_TARGET"; then
    return 0
  fi
  rm -f -- "$next"
  return 1
}

tlsset_configtest() { haproxy_test </dev/null; }

# A reload that ends HAProxy (a setting its configuration test let through) is seen by its processes, and the restore
# then starts the service: tlsset_alive and tlsset_start. A stopped HAProxy has nothing to reload.
tlsset_reload() { haproxy_runs || return 1; haproxy_reload </dev/null; }

tlsset_alive() { haproxy_runs; }

tlsset_start() { haproxy_start; }

tlsset_conflicts() {
  awk -v file="$TLSSET_TARGET" '
    { line++ }
    $1 == "bind" && match($0, /[ \t](ciphers|curves|ssl-min-ver)[ \t]/) {
      print file ":" line " bind " substr($0, RSTART + 1, RLENGTH - 2)
    }' "$TLSSET_TARGET"
}
}

# ---- The script's own code: what it reads for the report beside the agents' functions.

# listeners_<product>: one line per TLS site or listener: name, host, port and server name for the handshake,
# separated by FS. A wildcard address is asked on 127.0.0.1.
# probe_name NAMES: the server name a handshake sends to reach a site with these names: its first plain name, else a
# name under its first wildcard (*.example.com), else none.
probe_name() {
  local name
  local -a names=()
  read -ra names <<< "$1"
  for name in ${names[@]+"${names[@]}"}; do
    case "$name" in _|*'*'*|'~'*) ;; *) printf '%s' "$name"; return 0 ;; esac
  done
  for name in ${names[@]+"${names[@]}"}; do
    [[ "$name" != '*.'?* || "${name#\*.}" == *'*'* ]] || { printf 'sslbrain-probe.%s' "${name#\*.}"; return 0; }
  done
}

listeners_nginx() {
  local names port rest sni addresses host
  # A port every listen line gives an address of its own does not answer on 127.0.0.1: port and that address.
  addresses="$(awk '
    $1 == "listen" {
      a = $2; sub(/;.*$/, "", a); host = ""; port = a
      if (a ~ /^unix:/) next
      if (a ~ /^\[/) { host = a; sub(/\].*$/, "", host); sub(/^\[/, "", host); sub(/^.*\]:?/, "", port) }
      else if (a ~ /:/) { host = a; sub(/:[^:]*$/, "", host); sub(/^.*:/, "", port) }
      if (port !~ /^[0-9]+$/) next
      if (host == "" || host == "*" || host == "0.0.0.0" || host == "::") wild[port] = 1
      else if (!(port in first)) first[port] = host
    }
    END { for (port in first) if (!(port in wild)) print port, first[port] }' <<< "$CONF")"
  while IFS="$FS" read -r names port rest; do
    [ -n "$port" ] || continue
    sni="$(probe_name "$names")"
    [ -n "$names" ] && [ "$names" != _ ] || names="(default server)"
    host="$(awk -v port="$port" '$1 == port { print $2; exit }' <<< "$addresses")"
    printf '%s\n' "$names$FS${host:-127.0.0.1}$FS$port$FS$sni"
  done < <(conf_servers) | awk '!seen[$0]++'
}

listeners_apache() {
  local i host
  sb_apache_vhosts || return 0
  for ((i = 0; i < ${#SB_VH_NAME[@]}; i++)); do
    [ "${SB_VH_TLS[i]}" = true ] || continue
    host="${SB_VH_HOST[i]}"
    case "$host" in ''|'*'|_default_|0.0.0.0|::) host=127.0.0.1 ;; esac
    printf '%s\n' "${SB_VH_NAMES[i]:-(default VirtualHost)}$FS$host$FS${SB_VH_PORT[i]}$FS$(probe_name "${SB_VH_NAME[i]} ${SB_VH_NAMES[i]}")"
  done | awk '!seen[$0]++'
}

listeners_haproxy() {
  local frontend port path kind host
  conf_read
  while IFS="$FS" read -r frontend port path kind host; do
    [ -n "$port" ] || continue
    printf '%s\n' "$frontend$FS${host:-127.0.0.1}$FS$port$FS"
  done <<< "$ENTRIES" | awk '!seen[$0]++'
}

# directives_<product>: the TLS directives of the configuration outside the script's place, one per line:
# file:line, the part it sets (protocols, ciphers or groups), where it stands (server-wide, or the block that keeps
# it for itself) and the directive as written.
directives_nginx() {
  awk -v own="$TLSSET_TARGET" -v fs="$FS" '
    /^#sslbrain-file / { file = substr($0, 16); line[file] = 0; next }
    /^#sslbrain-back / { file = substr($0, 16); line[file]++; next }
    /^#sslbrain-/ { next }
    {
      line[file]++; text = $0; sub(/^[ \t]+/, "", text); sub(/[ \t]*;.*$/, "", text)
      code = $0; sub(/#.*/, "", code); opens = gsub(/\{/, "{", code); closes = gsub(/\}/, "}", code)
      if ($1 == "server" && opens > 0 && !inside) inside = depth + 1
      was = inside
      depth += opens - closes
      if (inside && depth < inside) inside = 0
    }
    file == own { next }
    $1 == "ssl_protocols" { part = "protocols" }
    $1 == "ssl_ciphers" { part = "ciphers" }
    $1 == "ssl_ecdh_curve" { part = "groups" }
    $1 == "ssl_conf_command" {
      part = ($2 ~ /Protocol$/) ? "protocols" : ($2 ~ /^(Groups|Curves)$/) ? "groups" : ($2 ~ /^Cipher/) ? "ciphers" : ""
    }
    part != "" { print file ":" line[file] fs part fs (was ? "a server block" : "http") fs text; part = "" }' <<< "$CONF"
}

directives_apache() {
  local file
  while IFS= read -r file; do
    [ "$file" != "$TLSSET_TARGET" ] || continue
    awk -v file="$file" -v fs="$FS" '
      { line++; d = tolower($1); text = $0; sub(/^[ \t]+/, "", text); sub(/[ \t\r]+$/, "", text); part = "" }
      d ~ /^<virtualhost(>|$)/ { inside = 1 }
      d ~ /^<\/virtualhost>/ { inside = 0 }
      d == "sslprotocol" { part = "protocols" }
      d == "sslciphersuite" || d == "sslhonorcipherorder" { part = "ciphers" }
      d == "sslopensslconfcmd" { part = ($2 ~ /Protocol$/) ? "protocols" : ($2 ~ /^(Groups|Curves)$/) ? "groups" : ($2 ~ /^Cipher/) ? "ciphers" : "" }
      part != "" { print file ":" line fs part fs (inside ? "a VirtualHost" : "server-wide") fs text }' "$file" 2>/dev/null || true
  done < <(sb_apache_ctl -t -D DUMP_INCLUDES 2>/dev/null | sed -n 's/^[[:space:]]*([^)]*)[[:space:]]*\(\/.*\)$/\1/p' | awk '!seen[$0]++')
}

directives_haproxy() {
  awk -v file="$TLSSET_TARGET" -v begin="$TLS_BEGIN" -v end="$TLS_END" -v fs="$FS" '
    { line++; text = $0; sub(/^[ \t]+/, "", text); part = "" }
    index($0, begin) == 1 { skip = 1 }
    skip { if ($0 == end) skip = 0; next }
    $1 == "ssl-default-bind-options" { part = "protocols" }
    $1 == "ssl-default-bind-ciphers" || $1 == "ssl-default-bind-ciphersuites" { part = "ciphers" }
    $1 == "ssl-default-bind-curves" { part = "groups" }
    part != "" { print file ":" line fs part fs "global" fs text; next }
    $1 == "bind" && match($0, /[ \t](ciphers|ciphersuites|curves|ssl-min-ver|ssl-max-ver|no-tlsv1[0-3]|force-tlsv1[0-3])([ \t]|$)/) {
      word = substr($0, RSTART + 1, RLENGTH - 1); sub(/[ \t]+$/, "", word)
      part = (word ~ /^cipher/) ? "ciphers" : (word == "curves") ? "groups" : "protocols"
      print file ":" line fs part fs "a bind line" fs text
    }' "$TLSSET_TARGET"
}

# include_<product>: what loads the script's place, with file and line, for the record --undo keeps.
include_nginx() {
  local file
  local -a files
  mapfile -t files <<< "$CONF_FILES"
  for file in ${files[@]+"${files[@]}"}; do
    [ -r "$file" ] || continue
    awk -v file="$file" -v relative="conf.d/*.conf" -v absolute="$(dirname -- "$TLSSET_TARGET")/*.conf" '
      $1 == "include" {
        value = $0; sub(/^[ \t]*include[ \t]+/, "", value); sub(/[ \t]*;.*$/, "", value)
        if (value ~ /^".*"$/) value = substr(value, 2, length(value) - 2)
        if (value == relative || value == absolute) { print file ":" NR ": include " value; exit }
      }' "$file"
  done | sed -n 1p
}

include_apache() {
  local main=/etc/apache2/apache2.conf
  [[ "$TLSSET_TARGET" != /etc/httpd/* ]] || main=/etc/httpd/conf/httpd.conf
  awk -v file="$main" 'tolower($1) ~ /^include(optional)?$/ && $2 ~ /(conf-enabled|conf\.d)\/\*(\.conf)?"?$/ { print file ":" NR ": " $1 " " $2; exit }' "$main" 2>/dev/null || true
}

include_haproxy() { printf '%s\n' "$TLSSET_TARGET: the section between $TLS_BEGIN and $TLS_END, read with the file"; }

# line_part LINE: the part a line of the script's place sets (protocols, ciphers or groups); nothing for the lines
# around them.
line_part() {
  case "$1" in
    *'ssl_conf_command MinProtocol '*|*'SSLProtocol '*|*'ssl-default-bind-options '*) echo protocols ;;
    *'ssl_conf_command CipherString '*|*'ssl_ciphers '*|*'SSLCipherSuite '*|*'SSLHonorCipherOrder '*|*'ssl-default-bind-ciphers '*) echo ciphers ;;
    *'ssl_conf_command Groups '*|*'ssl_ecdh_curve '*|*'SSLOpenSSLConfCmd Groups '*|*'ssl-default-bind-curves '*) echo groups ;;
  esac
}

part_chosen() { [[ ",$PARTS," == *",$1,"* ]]; }

# wanted_content CURRENT_FILE: what the script's place should hold. The agent's rendering of the profile gives the
# lines; a part that is not chosen keeps the lines the place has for it now. Nothing when no line is left.
wanted_content() {
  local current="$1" line part mode=head rendered
  local -a head=() tail=() protocols=() ciphers=() groups=()
  TLSSET_WANT_PROFILE=true
  TLSSET_WANT_MIN_PROTOCOL="$TLS_MIN_PROTOCOL"
  TLSSET_WANT_GROUPS="$WANT_GROUPS"
  rendered="$(tlsset_render)"
  while IFS= read -r line; do
    part="$(line_part "$line")"
    if [ -n "$part" ]; then
      mode="tail"
      tail=()
      ! part_chosen "$part" || case "$part" in
        protocols) protocols+=("$line") ;;
        ciphers) ciphers+=("$line") ;;
        groups) groups+=("$line") ;;
      esac
    elif [ "$mode" = head ]; then
      head+=("$line")
    else
      tail+=("$line")
    fi
  done <<< "$rendered"
  while IFS= read -r line; do
    part="$(line_part "$line")"
    [ -n "$part" ] || continue
    case "$part" in
      protocols) part_chosen protocols || protocols+=("$line") ;;
      ciphers) part_chosen ciphers || ciphers+=("$line") ;;
      groups) { part_chosen groups && [ -n "$WANT_GROUPS" ]; } || groups+=("$line") ;;
    esac
  done < "$current"
  [ $((${#protocols[@]} + ${#ciphers[@]} + ${#groups[@]})) -gt 0 ] || return 0
  local told=false
  for line in ${head[@]+"${head[@]}"}; do
    case "$line" in
      "${TLS_BEGIN:-# BEGIN sslbrain-tls}"*) printf '%s: %s; put back what was here before with: %s --undo\n' "${TLS_BEGIN:-# BEGIN sslbrain-tls}" "$MARK_OURS" "$SCRIPT_NAME" ;;
      '#'*) [ "$told" = true ] || printf '# TLS settings %s (%s).\n# Put back what was here before with: %s --undo\n' "$MARK_OURS" "$PAGE" "$SCRIPT_NAME"; told=true ;;
      *) printf '%s\n' "$line" ;;
    esac
  done
  printf '%s\n' ${protocols[@]+"${protocols[@]}"} ${ciphers[@]+"${ciphers[@]}"} ${groups[@]+"${groups[@]}"}
  [ ${#tail[@]} -eq 0 ] || printf '%s\n' "${tail[@]}"
}

# choose_listener: LOCAL_TLS_HOST, LOCAL_TLS_PORT and LOCAL_TLS_SNI for the handshake: the options, else the first
# TLS site of the configuration, else 127.0.0.1:443.
choose_listener() {
  local name host port sni
  IFS="$FS" read -r name host port sni < <("listeners_$PRODUCT" 2>/dev/null | sed -n 1p; echo) || true
  LOCAL_TLS_HOST="${GIVEN_HOST:-${host:-127.0.0.1}}"
  LOCAL_TLS_PORT="${GIVEN_PORT:-${port:-443}}"
  LOCAL_TLS_SNI="${GIVEN_SNI:-${sni:-}}"
}

show_events() {
  local event
  for event in ${EVENTS[@]+"${EVENTS[@]}"}; do say "  note: $event"; done
  EVENTS=()
}

show_lines() {   # TITLE FILE
  say "  $1"
  if [ -s "$2" ]; then sed 's/^/      /' "$2"; else say "      (nothing: the place is absent)"; fi
}

# ---- The state --undo works from.

# The state directory is root's own, and so is every file in it: --undo writes what they hold into the server's
# configuration.
state_trusted() {
  local file
  if [ -L "$STATE_DIR" ] || { [ -e "$STATE_DIR" ] && { [ ! -d "$STATE_DIR" ] || [ "$(stat -c %u -- "$STATE_DIR")" != 0 ]; }; }; then
    say "FAILED: $STATE_DIR is not a directory of root's own. Move it away and run the script again. Nothing was changed."
    return 1
  fi
  for file in "$STATE_DIR"/*; do
    [ -e "$file" ] || [ -L "$file" ] || continue
    if [ -L "$file" ] || [ ! -f "$file" ] || [ "$(stat -c %u -- "$file")" != 0 ]; then
      say "FAILED: $file is not a file of root's own. Move it away and run the script again. Nothing was changed."
      return 1
    fi
  done
}

state_ready() {
  state_trusted || return 1
  mkdir -p -- "$STATE_DIR" && chmod 0700 -- "$STATE_DIR"
}

# recorded_place: the place the script's first change was made in, from the record.
recorded_place() { sed -n 's/^place: //p' "$STATE_DIR/$PRODUCT.info" 2>/dev/null | sed -n 1p; }

# lock_run: one --apply or --undo at a time. Two at once would each save and put back what the other is changing.
# A run that was killed leaves its lock; it is taken over when its process is gone.
lock_run() {
  local holder
  if ! mkdir -- "$LOCK" 2>/dev/null; then
    holder="$(cat -- "$LOCK/pid" 2>/dev/null || true)"
    if [[ "$holder" =~ ^[0-9]+$ ]] && kill -0 "$holder" 2>/dev/null; then
      say "Another $SCRIPT_NAME (process $holder) is changing the TLS settings of this server. Wait for it and run again. Nothing was changed."
      exit 1
    fi
    mkdir -p -- "$LOCK" 2>/dev/null || return 0
  fi
  echo "$$" > "$LOCK/pid"
  trap 'rm -rf -- "$LOCK"' EXIT
}

state_has() { [ -f "$STATE_DIR/$PRODUCT.before" ] && [ -f "$STATE_DIR/$PRODUCT.written" ]; }

state_forget() { rm -f -- "$STATE_DIR/$PRODUCT.before" "$STATE_DIR/$PRODUCT.written" "$STATE_DIR/$PRODUCT.earlier" "$STATE_DIR/$PRODUCT.info"; }

# ---- Writing the script's place, with the agents' safety net.

# put_back REASON: the previous content again, tested and reloaded as the agent does it. Returns 1, or 4 when the
# previous settings could not be put back either.
put_back() {
  say "FAILED: $1"
  if _tlsset_restore; then
    show_events
    say "  The previous settings are back$([ -z "$TLSSET_RELOADED" ] || echo " and $TLSSET_PRODUCT is reloaded with them")."
    return 1
  fi
  show_events
  say "  The previous settings could NOT be put back automatically. Put what was there before in $TLSSET_TARGET,"
  say "  test the configuration and reload $TLSSET_PRODUCT."
  if cp -- "$TLSSET_PREVIOUS" "$STATE_DIR/$PRODUCT.previous" 2>/dev/null; then say "  What was there before is in $STATE_DIR/$PRODUCT.previous"
  else show_lines "What was there before:" "$TLSSET_PREVIOUS"; fi
  return 4
}

# switch_to FILE: the script's place gets FILE's content (an empty file removes it). TLSSET_PREVIOUS holds what is
# there now. 0 when the settings are active, or written and tested for a product that does not run.
switch_to() {
  local wanted="$1" output active=true
  TLSSET_RELOADED=""
  TLSSET_EXPECT_GROUP=""
  TLSSET_WAIT="$WAIT"
  if ! output="$(tlsset_configtest 2>&1)"; then
    say "REFUSED: $TLSSET_PRODUCT's configuration fails its own test before anything is changed, so nothing was written:"
    say "  $(_tlsset_last_lines "$output")"
    return 2
  fi
  if ! tlsset_put "$wanted"; then
    if [ "$(tlsset_current 2>/dev/null || true)" = "$(cat -- "$TLSSET_PREVIOUS")" ]; then
      say "FAILED: $TLSSET_TARGET could not be written. Nothing was changed."
      return 1
    fi
    put_back "$TLSSET_TARGET could not be written completely."; return
  fi
  if ! output="$(tlsset_configtest 2>&1)"; then
    put_back "$TLSSET_PRODUCT refused the settings in its configuration test, so nothing was reloaded: $(_tlsset_last_lines "$output")"; return
  fi
  say "  written: $TLSSET_TARGET; the configuration test passes"
  _tlsset_note_processes
  if ! _tlsset_running; then
    say "  $TLSSET_PRODUCT is not running and is not started: the settings apply when it starts."
    return 0
  fi
  TLSSET_RAN_BEFORE=true
  TLSSET_RELOADED=1
  if ! output="$(tlsset_reload 2>&1)"; then
    put_back "$TLSSET_PRODUCT did not reload with the settings: $(_tlsset_last_lines "$output")"; return
  fi
  TLSSET_RELOADS=$((TLSSET_RELOADS + 1))
  say "  reloaded: $TLSSET_PRODUCT (graceful)"
  # A graceful reload returns while the old processes still answer: the handshake is asked once new ones run, so
  # that it is theirs. A product that stopped at the reload has none, and the wait below says so.
  sb_tlsset_settled || true
  TLSSET_EXPECT_GROUP="$EXPECT_GROUP"
  _tlsset_wait_for_listener || active=false
  if [ "$active" = false ]; then
    if [ "$TLSSET_PROBE_OK" = true ]; then
      put_back "after the reload the handshake on $LOCAL_TLS_HOST:$LOCAL_TLS_PORT agrees on ${TLSSET_PROBE_GROUP:-no group}, not $EXPECT_GROUP, so this listener does not use the settings$(conflict_words)."; return
    elif [ "$TLSSET_BASELINE_OK" = true ]; then
      put_back "TLS stopped answering on $LOCAL_TLS_HOST:$LOCAL_TLS_PORT after the reload."; return
    elif ! _tlsset_running; then
      put_back "$TLSSET_PRODUCT ran before the reload with the settings and does not run after it."; return
    fi
    say "  not measured: no TLS answer on $LOCAL_TLS_HOST:$LOCAL_TLS_PORT before or after; confirmed by the configuration test only"
    return 0
  fi
  if [ "$CHECK_ONLY" = true ]; then
    # A process of the old generation may answer for a moment yet: asked again while one of them is still there.
    local asked=0
    while :; do
      TLSSET_PROBE_ANY=false sb_tlsset_probe -groups X25519
      [ "$TLSSET_PROBE_OK" = true ] && [ "$(_tlsset_old_processes_left)" -gt 0 ] && [ "$asked" -lt "$WAIT" ] || break
      sleep 1
      asked=$((asked + 1))
    done
    if [ "$TLSSET_PROBE_OK" = true ]; then
      put_back "a client that offers only X25519 still completes TLS 1.3 on $LOCAL_TLS_HOST:$LOCAL_TLS_PORT, so this listener does not use the settings$(conflict_words)."; return
    fi
    TLSSET_PROBE_ANY=true sb_tlsset_probe -tls1_2
    if [ "$TLSSET_PROBE_OK" = true ]; then
      put_back "TLS 1.2 is still answered on $LOCAL_TLS_HOST:$LOCAL_TLS_PORT, so this listener does not use the settings$(conflict_words)."; return
    fi
    TLSSET_PROBE_ANY=true sb_tlsset_probe
    say "  checked: a client with only X25519 and a client with only TLS 1.2 are refused"
  fi
  if [ "$TLSSET_PROBE_OK" = true ]; then
    say "  checked: the handshake on $LOCAL_TLS_HOST:$LOCAL_TLS_PORT answers$([ "$TLSSET_PROBE_TLS13" != true ] || echo ' with TLS 1.3')$([ -z "$TLSSET_PROBE_GROUP" ] || echo " and agrees on $TLSSET_PROBE_GROUP")"
  fi
  return 0
}

conflict_words() {
  local list
  list="$(tlsset_conflicts 2>/dev/null | tr '\n' ';' || true)"
  [ -z "$list" ] || printf ' (its own setting stands at: %s)' "${list%;}"
}

# prepare_switch: the handshake before the change (TLSSET_BASELINE_OK, TLSSET_GROUP_BEFORE). 2 when there is none
# and the product runs: a broken server could not be told from a working one afterwards.
prepare_switch() {
  choose_listener
  TLSSET_PROBE_ANY=true
  sb_tlsset_probe
  TLSSET_BASELINE_OK="$TLSSET_PROBE_OK"
  TLSSET_BASELINE_TLS13="$TLSSET_PROBE_TLS13"
  TLSSET_GROUP_BEFORE="$TLSSET_PROBE_GROUP"
  if [ "$TLSSET_BASELINE_OK" != true ] && _tlsset_running && [ "$FORCE" != true ]; then
    say "REFUSED: no TLS answer on $LOCAL_TLS_HOST:$LOCAL_TLS_PORT before the change, so the script could not tell afterwards whether"
    say "  $TLSSET_PRODUCT still serves. Name a TLS listener with --host, --port and --sni, or add --force. Nothing was changed."
    return 2
  fi
}

# apply_product: --apply for the product whose functions are loaded. Exit status as the script's.
apply_product() {
  local conflict wanted
  WANTED_FILE=""
  if ! tlsset_detect; then
    [ "${TLSSET_FAIL_CODE:-}" != not_installed ] || return 0
    say "$TLSSET_PRODUCT: REFUSED: ${TLSSET_FAIL_MESSAGE:-the server could not be read}. Nothing was changed."
    return 2
  fi
  sb_tlsset_pqc_capability
  say "$TLSSET_PRODUCT ${TLSSET_VERSION:-} on ${TLSSET_LIBRARY:-an unknown TLS library}"
  TLS_PROFILE=sslbrain_recommended
  TLS_MIN_PROTOCOL=TLSv1.2
  TLS_CIPHERS="$PROFILE_CIPHERS"
  WANT_GROUPS=""
  CHECK_ONLY=false
  EXPECT_GROUP=""
  if [ "$LEVEL" = only ]; then
    local why=""
    if [ "$TLSSET_PQC_CAPABLE" != true ]; then why="$TLSSET_PQC_REASON"
    elif ! part_chosen protocols || ! part_chosen groups; then why="--parts must hold both protocols and groups"
    elif [ "$PRODUCT" = nginx ] && [ "$TLS_CONF_COMMAND" != true ]; then why="nginx $TLSSET_VERSION has no ssl_conf_command (added in nginx 1.19.4) to set the lowest protocol with"
    elif ! _tlsset_client_knows_pqc; then why="this server's own openssl is older than 3.5 and cannot check the result, and a server that is set wrongly lets nobody in"
    fi
    if [ -n "$why" ]; then
      say "  REFUSED: --pqc only is set as a whole or not at all, and here it cannot: $why. Nothing was changed."
      return 2
    fi
    TLS_MIN_PROTOCOL=TLSv1.3
    WANT_GROUPS="$HYBRID_GROUPS"
    CHECK_ONLY=true
  elif [ "$LEVEL" = when-possible ] && part_chosen groups; then
    if [ "$TLSSET_PQC_CAPABLE" = true ]; then WANT_GROUPS="$PROFILE_GROUPS"
    else say "  note: post-quantum key exchange is not set: $TLSSET_PQC_REASON. The groups are left alone."; fi
  fi
  tlsset_prepare
  show_events

  TLSSET_PREVIOUS="$(mktemp "${TMPDIR:-/tmp}/sslbrain-tls-previous.XXXXXXXX")" && WANTED_FILE="$(mktemp "${TMPDIR:-/tmp}/sslbrain-tls-wanted.XXXXXXXX")" \
    || { say "  FAILED: no temporary file could be made in ${TMPDIR:-/tmp}. Nothing was changed."; return 1; }
  wanted="$WANTED_FILE"
  trap 'rm -f -- "$TLSSET_PREVIOUS" "$WANTED_FILE"' EXIT
  tlsset_current > "$TLSSET_PREVIOUS" || { say "  FAILED: $TLSSET_TARGET could not be read. Nothing was changed."; return 1; }
  if [ -s "$TLSSET_PREVIOUS" ] && ! state_has && [ "$FORCE" != true ] && [[ "$(cat -- "$TLSSET_PREVIOUS")" == *"$MARK_AGENT"* ]]; then
    say "  REFUSED: the sslbrain agent manages the TLS settings of this server ($TLSSET_TARGET); change them on the server's"
    say "  page in sslbrain. --force lets this script take the place over. Nothing was changed."
    return 2
  fi
  if state_has && [ -n "$(recorded_place)" ] && [ "$(recorded_place)" != "$TLSSET_TARGET" ]; then
    say "  REFUSED: an earlier --apply changed $(recorded_place), and $TLSSET_PRODUCT is now found with $TLSSET_TARGET (another"
    say "  instance or configuration). Run $SCRIPT_NAME --undo with the first one running, or put $STATE_DIR/$PRODUCT.before"
    say "  back by hand and remove $STATE_DIR/$PRODUCT.*. Nothing was changed."
    return 2
  fi
  # Put together in memory and compared with what reached the file: a full disk must not leave half the settings.
  local content
  content="$(wanted_content "$TLSSET_PREVIOUS")" && printf '%s' "${content:+$content$'\n'}" > "$wanted" && [ "$(cat -- "$wanted")" = "$content" ] \
    || { say "  FAILED: the settings could not be put together in ${TMPDIR:-/tmp}. Nothing was changed."; return 1; }
  if [ "$(cat -- "$TLSSET_PREVIOUS")" = "$content" ]; then
    # In place only when the running server uses it too: a run that was cut off between the write and the reload
    # left the file without the reload, and is finished here.
    choose_listener
    TLSSET_PROBE_ANY=false sb_tlsset_probe
    if [ -z "$WANT_GROUPS" ] || ! _tlsset_client_knows_pqc || ! _tlsset_running || [ "$TLSSET_PROBE_OK" != true ] || [ "$TLSSET_PROBE_GROUP" = "${WANT_GROUPS%%:*}" ]; then
      say "  Nothing to change: $TLSSET_TARGET already holds the chosen settings."
      return 0
    fi
    say "  $TLSSET_TARGET already holds the chosen settings, but the running $TLSSET_PRODUCT does not use them: its handshake agrees on"
    say "  ${TLSSET_PROBE_GROUP:-no group}, not ${WANT_GROUPS%%:*}. The configuration is tested and $TLSSET_PRODUCT reloaded."
  fi
  if [ ! -s "$wanted" ]; then
    say "  Nothing to set here for the chosen parts; $TLSSET_TARGET is left as it is."
    return 0
  fi
  while IFS= read -r conflict; do
    [ -z "$conflict" ] || say "  note: $conflict keeps its own setting; the script's settings do not apply to that block"
  done < <(tlsset_conflicts 2>/dev/null || true)
  show_lines "now in $TLSSET_TARGET:" "$TLSSET_PREVIOUS"
  show_lines "wanted:" "$wanted"
  if [ "$DRY_RUN" = true ]; then
    say "  Would write it, test the configuration, reload $TLSSET_PRODUCT gracefully and check a TLS handshake (--dry-run: nothing is written)."
    return 0
  fi
  state_ready || return 1
  prepare_switch || return
  # The group the handshake must agree on: the first one set, where the listener spoke TLS 1.3 before or the
  # protocols are set too, and this server's own openssl can offer it.
  if [ -n "$WANT_GROUPS" ] && _tlsset_client_knows_pqc && { [ "$TLSSET_BASELINE_TLS13" = true ] || [ "$LEVEL" = only ]; }; then
    EXPECT_GROUP="${WANT_GROUPS%%:*}"
  fi
  # What was there before the script's first change is kept until --undo; a later --apply does not replace it.
  # What the script wrote is recorded before the write, so a run that is cut off leaves a place --undo knows.
  local earlier=false status=0 now
  if state_has; then
    earlier=true
    cp -- "$STATE_DIR/$PRODUCT.written" "$STATE_DIR/$PRODUCT.earlier" || { say "  FAILED: $STATE_DIR could not be written. Nothing was changed."; return 1; }
  else
    printf 'place: %s\nloaded by: %s\nfirst changed: %s\n' "$TLSSET_TARGET" "$("include_$PRODUCT" 2>/dev/null || true)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATE_DIR/$PRODUCT.info" \
      && cp -- "$TLSSET_PREVIOUS" "$STATE_DIR/$PRODUCT.before" \
      || { say "  FAILED: $STATE_DIR could not be written, so --undo would have nothing to work from. Nothing was changed."; return 1; }
  fi
  cp -- "$wanted" "$STATE_DIR/$PRODUCT.written" || { say "  FAILED: $STATE_DIR could not be written. Nothing was changed."; return 1; }
  switch_to "$wanted" || status=$?
  if [ "$status" != 0 ]; then
    now="$(tlsset_current 2>/dev/null || true)"
    if [ "$now" = "$(cat -- "$STATE_DIR/$PRODUCT.before")" ]; then
      state_forget   # nothing of the script's is left in the place
    elif [ "$earlier" = true ] && [ "$now" != "$content" ]; then
      # The run left what was there: the record of the earlier --apply stands, also against a later change by hand.
      mv -- "$STATE_DIR/$PRODUCT.earlier" "$STATE_DIR/$PRODUCT.written"
    fi
    rm -f -- "$STATE_DIR/$PRODUCT.earlier"
    [ "$status" != 4 ] || status=1
    return "$status"
  fi
  rm -f -- "$STATE_DIR/$PRODUCT.earlier"
  printf 'last changed: %s (%s, level %s, parts %s)\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$SCRIPT_VERSION" "$LEVEL" "$PARTS" >> "$STATE_DIR/$PRODUCT.info"
  say "  Done. Undo: sudo $0 --undo"
}

# undo_product: --undo for the product whose functions are loaded.
undo_product() {
  local current status=0
  state_has || return 0
  if ! tlsset_detect; then
    say "${TLSSET_PRODUCT:-$PRODUCT}: FAILED: ${TLSSET_FAIL_MESSAGE:-the server could not be read}; what the script changed is not put back."
    return 1
  fi
  if [ -n "$(recorded_place)" ] && [ "$(recorded_place)" != "$TLSSET_TARGET" ]; then
    say "$TLSSET_PRODUCT: FAILED: the script changed $(recorded_place), and $TLSSET_PRODUCT is now found with $TLSSET_TARGET (another instance"
    say "  or configuration). Nothing is put back. What was there before the script is in $STATE_DIR/$PRODUCT.before."
    return 1
  fi
  say "$TLSSET_PRODUCT: putting back what $SCRIPT_NAME changed in $TLSSET_TARGET"
  TLSSET_PREVIOUS="$(mktemp "${TMPDIR:-/tmp}/sslbrain-tls-previous.XXXXXXXX")" \
    || { say "  FAILED: no temporary file could be made in ${TMPDIR:-/tmp}. Nothing was changed."; return 1; }
  trap 'rm -f -- "$TLSSET_PREVIOUS"' EXIT
  tlsset_current > "$TLSSET_PREVIOUS" || { say "  FAILED: $TLSSET_TARGET could not be read. Nothing was changed."; return 1; }
  current="$(cat -- "$TLSSET_PREVIOUS")"
  if [ "$current" = "$(cat -- "$STATE_DIR/$PRODUCT.before")" ]; then
    say "  already as before the script."
    [ "$DRY_RUN" = true ] || state_forget
    return 0
  fi
  if [ "$current" != "$(cat -- "$STATE_DIR/$PRODUCT.written")" ] && [ "$FORCE" != true ]; then
    say "  left alone: $TLSSET_TARGET is not what the script wrote; someone changed it since."
    say "  $SCRIPT_NAME --undo --force puts back what was there before the script anyway."
    return 1
  fi
  show_lines "now:" "$TLSSET_PREVIOUS"
  show_lines "before the script:" "$STATE_DIR/$PRODUCT.before"
  if [ "$DRY_RUN" = true ]; then say "  Would put it back, test the configuration and reload $TLSSET_PRODUCT (--dry-run: nothing is written)."; return 0; fi
  CHECK_ONLY=false
  EXPECT_GROUP=""
  FORCE=true prepare_switch
  switch_to "$STATE_DIR/$PRODUCT.before" || status=$?
  [ "$status" = 0 ] || { [ "$status" != 4 ] || status=1; return "$status"; }
  state_forget
  say "  Everything is back as it was before the script."
}

# ---- The report: each product gives records, one per line with fields separated by FS, which are shown as text,
# JSON or HTML.

record() { local IFS="$FS"; printf '%s\n' "$*"; }

# ---- The rating: sslbrain's list of 4 December 2026, after NSA's "Immediate Actions to Push Toward Post-Quantum"
# (2 December 2026) and Mozilla's TLS guidelines. Four levels; the sslbrain overview uses the same ones.

RATING_FOOTNOTE='* May be broken.'
# The groups a listener is asked for, one at a time, by the names openssl's client takes.
RATING_GROUPS="X25519MLKEM768 SecP256r1MLKEM768 SecP384r1MLKEM1024 X25519 X448 P-256 P-384 P-521"
# The kinds of cipher suite of TLS 1.2 and older that the list names, as openssl cipher strings. A listener is offered
# one kind at a time, so a suite it would not choose by itself still shows: RSA key transport, NULL, anonymous, 3DES,
# RC4, and CBC with ECDHE or DHE.
RATING_CIPHER_KINDS=(kRSA eNULL aNULL 3DES RC4 'ECDHE+SHA1:ECDHE+SHA256:ECDHE+SHA384:DHE+SHA1:DHE+SHA256:!aNULL:!eNULL:!3DES:!RC4')
HANDSHAKE_STALLED='set-linux-server-tls: no answer within 300 seconds'

rating_text() {
  case "$1" in
    good) echo 'Use' ;;
    fallback) echo 'Works in a transition' ;;
    remove_now) echo 'Remove now (our interpretation)*' ;;
    broken) echo 'Removal recommended long ago' ;;
    *) echo 'not in the list' ;;
  esac
}

# The three hybrid groups are the ones to use. NSA keeps P-384 and P-521 of the elliptic curves and asks for every other one to
# be removed. Another name has no rating.
rate_group() {
  case "$1" in
    X25519MLKEM768|SecP256r1MLKEM768|SecP384r1MLKEM1024) echo good ;;
    P-384|P-521) echo fallback ;;
    X25519|X448|P-256) echo remove_now ;;
  esac
}

# group_name NAME: a group as openssl's client prints it, by the name the client takes.
group_name() {
  case "$1" in
    prime256v1|secp256r1) echo P-256 ;;
    secp384r1) echo P-384 ;;
    secp521r1) echo P-521 ;;
    *) echo "$1" ;;
  esac
}

# rate_cipher NAME: RATED and RATED_WHY, the worst of what the suite's name says about its key exchange and its
# cipher, by openssl's names and the TLS 1.3 names. A suite of TLS 1.2 and older is never better than TLS 1.2
# itself. A name that says nothing the list knows has no rating.
rate_cipher() {
  local name="$1" rule level why worst="" rank best=-1
  local -a found=()
  RATED=""; RATED_WHY=""
  # level, pattern, the part of the suite it names (_ for a space)
  for rule in 'broken NULL NULL' 'broken RC4 RC4' 'broken DES-CBC3 3DES' 'broken DES-CBC- DES' 'broken ^EXP(1024)?- EXPORT' \
              'broken ^(ADH|AECDH)- anonymous' \
              'broken ^(RSA-PSK-|AES|CAMELLIA|ARIA|SEED|IDEA|DES|RC4|RC2|NULL) RSA_key_transport' \
              'broken ^(DH|ECDH)- static_DH' 'remove_now ^(DHE|EDH)- DHE' \
              'remove_now (AES|CAMELLIA)(128|256)-SHA(256|384)?$|SEED-SHA$|-CBC-|IDEA CBC' \
              'fallback AES128-GCM AES-128-GCM' 'fallback AES_128_GCM AES-128-GCM' 'fallback CHACHA20 ChaCha20-Poly1305' \
              'good AES256-GCM AES-256-GCM' 'good AES_256_GCM AES-256-GCM'; do
    read -r level rule why <<< "$rule"
    [[ "$name" =~ $rule ]] || continue
    found+=("$level ${why//_/ }")
  done
  for rule in ${found[@]+"${found[@]}"}; do
    level="${rule%% *}"
    case "$level" in good) rank=0 ;; fallback) rank=1 ;; remove_now) rank=2 ;; *) rank=3 ;; esac
    [ "$rank" -le "$best" ] || { best="$rank"; worst="$level"; }
  done
  for rule in ${found[@]+"${found[@]}"}; do
    [ "${rule%% *}" != "$worst" ] || RATED_WHY="${RATED_WHY:+$RATED_WHY, }${rule#* }"
  done
  if [ "$worst" = good ] && [[ "$name" != TLS_* ]]; then worst=fallback; RATED_WHY="TLS 1.2"; fi
  RATED="$worst"
}

# rate_certificate: from `openssl x509 -noout -text` on stdin, CERT_KEY and CERT_HASH with CERT_KEY_RATED and
# CERT_HASH_RATED.
rate_certificate() {
  local text type="" bits="" curve="" signature=""
  text="$(cat)"
  CERT_KEY=""; CERT_KEY_RATED=""; CERT_HASH=""; CERT_HASH_RATED=""
  if [[ "$text" =~ Public\ Key\ Algorithm:\ ([A-Za-z0-9_.-]+) ]]; then type="${BASH_REMATCH[1]}"; fi
  [ -n "$type" ] || return 0
  if [[ "$text" =~ Public-Key:\ \(([0-9]+)\ bit ]]; then bits="${BASH_REMATCH[1]}"; fi
  if [[ "$text" =~ ASN1\ OID:\ ([A-Za-z0-9_.-]+) ]]; then curve="${BASH_REMATCH[1]}"; fi
  case "$type" in
    rsaEncryption|rsassaPss)
      if [ -z "$bits" ]; then CERT_KEY="RSA, size not read"
      else
        CERT_KEY="RSA $bits"
        if [ "$bits" -ge 3072 ]; then CERT_KEY_RATED=good; elif [ "$bits" -ge 2048 ]; then CERT_KEY_RATED=fallback; else CERT_KEY_RATED=broken; fi
      fi ;;
    id-ecPublicKey)
      case "$curve" in
        prime256v1) CERT_KEY="ECC P-256"; CERT_KEY_RATED=remove_now ;;
        secp384r1) CERT_KEY="ECC P-384"; CERT_KEY_RATED=good ;;
        secp521r1) CERT_KEY="ECC P-521"; CERT_KEY_RATED=good ;;
        '') CERT_KEY="ECC, curve not read" ;;
        *) CERT_KEY="ECC $curve"; CERT_KEY_RATED=remove_now ;;
      esac ;;
    ED25519) CERT_KEY="Ed25519"; CERT_KEY_RATED=remove_now ;;
    ED448) CERT_KEY="Ed448"; CERT_KEY_RATED=remove_now ;;
    dsaEncryption) CERT_KEY="DSA"; CERT_KEY_RATED=remove_now ;;
    *) CERT_KEY="type $type" ;;
  esac
  if [[ "$text" =~ Signature\ Algorithm:\ ([A-Za-z0-9_.-]+) ]]; then signature="${BASH_REMATCH[1]}"; fi
  # RSASSA-PSS names its hash on a line of its own.
  if [ "$signature" = rsassaPss ] && [[ "$text" =~ Hash\ Algorithm:\ ([A-Za-z0-9_.-]+) ]]; then signature="${BASH_REMATCH[1]}"; fi
  case "${signature,,}" in
    *sha256*) CERT_HASH="SHA-256"; CERT_HASH_RATED=good ;;
    *sha384*) CERT_HASH="SHA-384"; CERT_HASH_RATED=good ;;
    *sha512*) CERT_HASH="SHA-512"; CERT_HASH_RATED=good ;;
    *sha1*) CERT_HASH="SHA-1"; CERT_HASH_RATED=broken ;;
    *md5*) CERT_HASH="MD5"; CERT_HASH_RATED=broken ;;
    *) CERT_HASH="not read (signature type ${signature:-unknown})" ;;
  esac
}

# handshake ARGS...: what openssl's client prints for one handshake with the listener (LOCAL_TLS_*). A listener
# that takes the connection and then says nothing is given up after five minutes, with a line that says so.
handshake() {
  local peer="$LOCAL_TLS_HOST:$LOCAL_TLS_PORT" status=0
  [[ "$LOCAL_TLS_HOST" != *:* ]] || peer="[$LOCAL_TLS_HOST]:$LOCAL_TLS_PORT"
  local -a args=(s_client -connect "$peer")
  [[ -z "$LOCAL_TLS_SNI" || "$LOCAL_TLS_SNI" == *'*'* ]] || args+=(-servername "$LOCAL_TLS_SNI")
  if command -v timeout >/dev/null 2>&1; then
    timeout 300 openssl "${args[@]}" "$@" </dev/null 2>&1 || status=$?
    [ "$status" != 124 ] || printf '%s\n' "$HANDSHAKE_STALLED"
  else openssl "${args[@]}" "$@" </dev/null 2>&1 || true; fi
}

# ask ARGS...: one handshake into ASKED; fails when the listener stopped answering.
ask() {
  ASKED="$(handshake "$@")"
  [[ "$ASKED" != *"$HANDSHAKE_STALLED"* ]]
}

# rate_listener NAME TLS13 TLS12 OLDER: the rating records of a listener that answers, from what measure found and
# from handshakes of its own: one per group, the cipher suites it chooses, one per kind of old cipher suite, one
# for the certificate. A listener that stops answering on the way is not asked again.
rate_listener() {
  local name="$1" tls13="$2" tls12="$3" older="$4" version group kind cipher seen=" " agreed
  local stalled="the listener stopped answering; the rest is not rated"
  [ "$tls13" != yes ] || record rating "$PRODUCT" "$name" protocol "TLS 1.3" good ""
  [ "$tls12" != yes ] || record rating "$PRODUCT" "$name" protocol "TLS 1.2" fallback "with ECDHE and an AEAD cipher"
  for version in "TLS 1.1" "TLS 1.0"; do
    [[ "$older" != *"$version"* ]] || record rating "$PRODUCT" "$name" protocol "$version" broken ""
  done
  # Offered one group only, the listener agrees to it or refuses. An answer whose key share is in another group, or
  # in none (RSA key transport, DHE with the server's own parameters), is not an answer about the group.
  for group in $RATING_GROUPS; do
    ask -brief -groups "$group" || { record rating "$PRODUCT" "$name" note "$stalled" "" ""; return 0; }
    [[ $'\n'"$ASKED" == *$'\n''Protocol version: '* ]] || continue
    if [[ "$ASKED" =~ Negotiated\ TLS1\.3\ group:\ ([A-Za-z0-9_-]+) ]] \
       || [[ "$ASKED" =~ (Peer|Server)\ Temp\ Key:\ (ECDH,\ )?([A-Za-z0-9_-]+), ]]; then
      agreed="$(group_name "${BASH_REMATCH[${#BASH_REMATCH[@]}-1]}")"
      [ "${agreed,,}" != "${group,,}" ] || record rating "$PRODUCT" "$name" group "$group" "$(rate_group "$group")" ""
    fi
  done
  if [ "$tls12" = yes ] || [ -n "$older" ]; then
    ask -brief -no_tls1_3 -cipher 'DHE:@SECLEVEL=0' || { record rating "$PRODUCT" "$name" note "$stalled" "" ""; return 0; }
    if [[ "$ASKED" =~ (Peer|Server)\ Temp\ Key:\ DH,\ ([0-9]+)\ bits ]]; then
      if [ "${BASH_REMATCH[2]}" -le 1024 ]; then record rating "$PRODUCT" "$name" group "DHE ${BASH_REMATCH[2]} bits (TLS 1.2 and older)" broken ""
      else record rating "$PRODUCT" "$name" group "DHE ${BASH_REMATCH[2]} bits (TLS 1.2 and older)" remove_now ""; fi
    fi
  fi
  for kind in 1_3 1_2 "${RATING_CIPHER_KINDS[@]}"; do
    case "$kind" in
      1_3) [ "$tls13" = yes ] || continue
           ask -brief -tls1_3 || { record rating "$PRODUCT" "$name" note "$stalled" "" ""; return 0; }
           agreed="chosen for TLS 1.3" ;;
      1_2) [ "$tls12" = yes ] || continue
           ask -brief -tls1_2 || { record rating "$PRODUCT" "$name" note "$stalled" "" ""; return 0; }
           agreed="chosen for TLS 1.2" ;;
      *) [ "$tls12" = yes ] || [ -n "$older" ] || continue
         ask -brief -no_tls1_3 -cipher "$kind:@SECLEVEL=0" || { record rating "$PRODUCT" "$name" note "$stalled" "" ""; return 0; }
         agreed="accepted when offered" ;;
    esac
    [[ $'\n'"$ASKED" == *$'\n''Protocol version: '* ]] && [[ "$ASKED" =~ Ciphersuite:\ ([A-Za-z0-9_-]+) ]] || continue
    cipher="${BASH_REMATCH[1]}"
    [[ "$seen" != *" $cipher "* ]] || continue
    seen="$seen$cipher "
    rate_cipher "$cipher"
    record rating "$PRODUCT" "$name" "cipher suite" "$cipher ($agreed)" "$RATED" "$RATED_WHY"
  done
  ask || { record rating "$PRODUCT" "$name" note "$stalled" "" ""; return 0; }
  rate_certificate < <(printf '%s\n' "$ASKED" | openssl x509 -noout -text 2>/dev/null || true)
  [ -z "$CERT_KEY" ] || record rating "$PRODUCT" "$name" "certificate key" "$CERT_KEY" "$CERT_KEY_RATED" ""
  [ -z "$CERT_HASH" ] || record rating "$PRODUCT" "$name" "signature hash" "$CERT_HASH" "$CERT_HASH_RATED" ""
}

# measure NAME: the handshakes with one listener (LOCAL_TLS_*), as a record.
measure() {
  local tls13=no group="" tls12=no old="" weak=no version
  TLSSET_PROBE_ANY=true sb_tlsset_probe
  if [ "$TLSSET_PROBE_OK" != true ]; then
    record listener "$PRODUCT" "$1" "$LOCAL_TLS_HOST" "$LOCAL_TLS_PORT" "$LOCAL_TLS_SNI" "no answer" "" "" "" "" ""
    return 0
  fi
  TLSSET_PROBE_ANY=false sb_tlsset_probe
  [ "$TLSSET_PROBE_OK" != true ] || { tls13=yes; group="$TLSSET_PROBE_GROUP"; }
  TLSSET_PROBE_ANY=true sb_tlsset_probe -tls1_2
  if [ "$TLSSET_PROBE_OK" = true ]; then
    tls12=yes
    [ -n "$group" ] || group="$TLSSET_PROBE_GROUP"
    TLSSET_PROBE_ANY=true sb_tlsset_probe -tls1_2 -cipher "$OLD_CIPHERS"
    [ "$TLSSET_PROBE_OK" != true ] || weak=yes
  fi
  for version in tls1_1 tls1; do
    TLSSET_PROBE_ANY=true sb_tlsset_probe "-$version" -cipher 'DEFAULT:@SECLEVEL=0'
    [ "$TLSSET_PROBE_OK" != true ] || old="${old:+$old, }$([ "$version" = tls1 ] && echo 'TLS 1.0' || echo 'TLS 1.1')"
  done
  record listener "$PRODUCT" "$1" "$LOCAL_TLS_HOST" "$LOCAL_TLS_PORT" "$LOCAL_TLS_SNI" answers "$tls13" "$group" "$tls12" "$old" "$weak"
  rate_listener "$1" "$tls13" "$tls12" "$old" >> "$REPORT_TMP.ratings"
}

# report_product: the records of the product whose functions are loaded.
report_product() {
  local problem="" place=absent running=no name host port sni count=0 where part scope text
  local hybrid=0 tls13=0 answered=0 old="" weak=0 own_groups="" run="sudo $0" l_state l_tls13 l_group l_tls12 l_old l_weak
  if ! tlsset_detect; then
    [ "${TLSSET_FAIL_CODE:-}" != not_installed ] || return 0
    problem="${TLSSET_FAIL_MESSAGE:-the TLS settings cannot be set on this server}"
  fi
  sb_tlsset_pqc_capability
  ! _tlsset_running || running=yes
  rm -f -- "$REPORT_TMP.ratings"
  if [ -n "${TLSSET_TARGET:-}" ] && [ -z "$problem" ]; then
    text="$(tlsset_current 2>/dev/null || true)"
    if [ -n "$text" ]; then
      place="present"
      [[ "$text" != *"$MARK_OURS"* ]] || place="set by this script"
      [[ "$text" != *"$MARK_AGENT"* ]] || place="set by the sslbrain agent"
    fi
  fi
  record product "$PRODUCT" "$TLSSET_PRODUCT" "${TLSSET_VERSION:-}" "${TLSSET_LIBRARY:-not read}" "$running" "${TLSSET_TARGET:-}" "$place" "$TLSSET_PQC_CAPABLE" "${TLSSET_PQC_REASON:-}"
  [ -z "$problem" ] || record verdict "$PRODUCT" INFO "Settings" "$problem" "Read the report's other lines; the script does not write here"
  # What the own place sets, in its order: the protocols, the cipher suites and the groups.
  if [ "$place" != absent ]; then
    while IFS= read -r where; do
      part="$(line_part "$where")"
      [ -z "$part" ] || record directive "$PRODUCT" "$TLSSET_TARGET" "$part" "server-wide ($place)" "$(printf '%s' "$where" | sed 's/^[[:space:]]*//')"
    done <<< "$text"
  fi

  while IFS="$FS" read -r where part scope text; do
    [ -n "$where" ] || continue
    record directive "$PRODUCT" "$where" "$part" "$scope" "$text"
    [ "$part" != groups ] || [[ "$text" == *MLKEM* ]] || own_groups="${own_groups:+$own_groups; }$where ($text)"
  done < <("directives_$PRODUCT" 2>/dev/null | awk '!seen[$0]++' || true)

  while IFS="$FS" read -r name host port sni; do
    [ -n "$port" ] || continue
    count=$((count + 1))
    LOCAL_TLS_HOST="${GIVEN_HOST:-$host}"; LOCAL_TLS_PORT="${GIVEN_PORT:-$port}"; LOCAL_TLS_SNI="${GIVEN_SNI:-$sni}"
    # A product that does not run answers nothing; whatever answers on its port is another program.
    if [ "$count" -gt 12 ]; then record listener "$PRODUCT" "$name" "$LOCAL_TLS_HOST" "$LOCAL_TLS_PORT" "$LOCAL_TLS_SNI" "not measured" "" "" "" "" ""
    elif [ "$running" = yes ]; then measure "$name"
    else record listener "$PRODUCT" "$name" "$LOCAL_TLS_HOST" "$LOCAL_TLS_PORT" "$LOCAL_TLS_SNI" "no answer" "" "" "" "" ""; fi
  done < <("listeners_$PRODUCT" 2>/dev/null || true) > "$REPORT_TMP.listeners"
  cat -- "$REPORT_TMP.listeners"
  while IFS="$FS" read -r _ _ name host port sni l_state l_tls13 l_group l_tls12 l_old l_weak; do
    [ "$l_state" = answers ] || continue
    answered=$((answered + 1))
    [ "$l_tls13" != yes ] || tls13=$((tls13 + 1))
    [ "$l_tls13" != yes ] || [ "$l_group" != "$TLSSET_PQC_GROUP" ] || hybrid=$((hybrid + 1))
    [ -z "$l_old" ] || old="$l_old"
    [ "$l_weak" != yes ] || weak=$((weak + 1))
  done < "$REPORT_TMP.listeners"
  rm -f -- "$REPORT_TMP.listeners"
  # The ratings follow the listeners they belong to.
  [ ! -f "$REPORT_TMP.ratings" ] || { cat -- "$REPORT_TMP.ratings"; rm -f -- "$REPORT_TMP.ratings"; }
  [ "$count" -le 12 ] || record verdict "$PRODUCT" INFO "Listeners" "$count TLS sites found; the first 12 are measured" "Measure another with --host, --port and --sni"

  if [ "$TLSSET_PQC_CAPABLE" != true ]; then
    record verdict "$PRODUCT" UPGRADE "Post-quantum key exchange" "${TLSSET_PQC_REASON:-the TLS library has none}" "Move to a release where $TLSSET_PRODUCT runs on OpenSSL 3.5 or later (Debian 13, Ubuntu 26.04, RHEL 10.1)"
  elif ! _tlsset_client_knows_pqc; then
    record verdict "$PRODUCT" INFO "Post-quantum key exchange" "$TLSSET_PRODUCT can, but this server's own openssl is older than 3.5 and cannot offer $TLSSET_PQC_GROUP, so it was not measured" "$run --apply --parts groups"
  elif [ "$answered" = 0 ]; then
    record verdict "$PRODUCT" INFO "Post-quantum key exchange" "no TLS listener of $TLSSET_PRODUCT answered, so nothing was measured${own_groups:+; own group list at $own_groups}" "$([ "$running" = yes ] && echo 'Name a listener with --host, --port and --sni' || echo "Start $TLSSET_PRODUCT and run the script again")"
  elif [ "$tls13" -gt 0 ] && [ "$hybrid" = "$tls13" ]; then
    record verdict "$PRODUCT" OK "Post-quantum key exchange" "$hybrid of $answered listeners agree on $TLSSET_PQC_GROUP" ""
  elif [ "$tls13" = 0 ]; then
    record verdict "$PRODUCT" APPLY "Post-quantum key exchange" "no listener answers TLS 1.3, which post-quantum key exchange needs" "$run --apply"
  else
    record verdict "$PRODUCT" APPLY "Post-quantum key exchange" "$hybrid of $tls13 TLS 1.3 listeners agree on $TLSSET_PQC_GROUP${own_groups:+; the configuration has its own group list without it at $own_groups}" "$run --apply --parts groups"
  fi
  if [ "$answered" -gt 0 ]; then
    if [ -n "$old" ]; then record verdict "$PRODUCT" APPLY "Old protocols" "$old answered" "$run --apply --parts protocols"
    else record verdict "$PRODUCT" OK "Old protocols" "no answer to TLS 1.0 or 1.1, as far as this server's openssl can offer them" ""; fi
    if [ "$weak" -gt 0 ]; then record verdict "$PRODUCT" APPLY "Cipher suites" "$weak of $answered listeners accept a TLS 1.2 cipher suite outside the profile (RSA key exchange or CBC)" "$run --apply --parts ciphers"
    else record verdict "$PRODUCT" OK "Cipher suites" "no TLS 1.2 cipher suite outside the profile was accepted" ""; fi
  fi
  if [ -z "$problem" ]; then
    while IFS= read -r text; do
      [ -z "$text" ] || record verdict "$PRODUCT" CONFIG "Own setting" "$text keeps its own setting; the script's settings do not apply to that block" "Change it there, or remove it so the block takes the server-wide settings"
    done < <(tlsset_conflicts 2>/dev/null || true)
  fi
  [ "$place" != "set by this script" ] || record verdict "$PRODUCT" INFO "Undo" "$TLSSET_TARGET is set by this script" "$run --undo puts back what was there before"
  [ "$running" = yes ] || record verdict "$PRODUCT" INFO "Service" "$TLSSET_PRODUCT is installed and not running" ""
}

# up_since: when this server last started, in UTC.
up_since() {
  local seconds
  seconds="$(cut -d. -f1 /proc/uptime 2>/dev/null || true)"
  [[ "$seconds" =~ ^[0-9]+$ ]] && date -u -d "@$(($(date +%s) - seconds))" '+%Y-%m-%d %H:%M UTC' 2>/dev/null || echo unknown
}

html() { local s="$1"; s="${s//&/&amp;}"; s="${s//</&lt;}"; s="${s//>/&gt;}"; s="${s//\"/&quot;}"; printf '%s' "$s"; }

report_text() {
  local kind a b c d e f g h i j k any=false rated=false
  say "$SCRIPT_NAME $SCRIPT_VERSION   $PAGE"
  say ""
  say "Server       $(hostname 2>/dev/null || echo unknown), $(sed -n 's/^PRETTY_NAME="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' /etc/os-release 2>/dev/null | sed -n 1p)"
  say "Last start   $(up_since)"
  say "openssl      $(openssl version 2>/dev/null || echo 'not installed: no handshake can be measured')"
  [ "$(id -u)" = 0 ] || say "Note         not run as root: parts of the configuration may be unreadable"
  while IFS="$FS" read -r kind a b c d e f g h i j k; do
    case "$kind" in
      product)
        any=true
        say ""
        say "== $b $c"
        say "TLS library  $d"
        say "Running      $e"
        say "Own place    ${f:-none} ($g)"
        say "Post-quantum $([ "$h" = true ] && echo 'the library can' || echo "the library cannot: $i")" ;;
      directive) say "  directive  $b  [$c, $d]  $e" ;;
      listener)
        if [ "$f" = answers ]; then
          say "  listener   $b  $c:$d${e:+ (SNI $e)}  TLS 1.3 $g${h:+, group $h}; TLS 1.2 $i; older: ${j:-no}; cipher suites outside the profile: $k"
        else say "  listener   $b  $c:$d${e:+ (SNI $e)}  $([ "$f" = "not measured" ] && echo 'not measured' || echo 'no TLS answer')"; fi ;;
      rating)
        rated=true
        if [ "$c" = note ]; then say "  rating     $b  $d"
        else say "  rating     $b  $c $d: $(rating_text "$e")$([ -z "$f" ] || [ "$e" = good ] || echo " ($f)")"; fi ;;
      verdict)
        printf '  %-10s %s: %s\n' "[$b]" "$c" "$d"
        [ -z "$e" ] || say "             next: $e" ;;
    esac
  done < "$1"
  [ "$rated" != true ] || say "
Rating: $(rating_text good); $(rating_text fallback); $(rating_text remove_now); $(rating_text broken).  $RATING_FOOTNOTE"
  [ "$any" = true ] || say "
No nginx, Apache httpd or HAProxy was found on this server."
}

report_json() {
  local kind a b c d e f g h i j k first=true sub
  printf '{"script":%s,"page":%s,"host":%s,"last_start":%s,"openssl":%s,' "$(sb_json "$SCRIPT_NAME $SCRIPT_VERSION")" "$(sb_json "$PAGE")" \
    "$(sb_json "$(hostname 2>/dev/null || true)")" "$(sb_json "$(up_since)")" "$(sb_json "$(openssl version 2>/dev/null || true)")"
  printf '"rating_levels":{"good":%s,"fallback":%s,"remove_now":%s,"broken":%s},"rating_footnote":%s,"products":[' "$(sb_json "$(rating_text good)")" \
    "$(sb_json "$(rating_text fallback)")" "$(sb_json "$(rating_text remove_now)")" "$(sb_json "$(rating_text broken)")" "$(sb_json "$RATING_FOOTNOTE")"
  while IFS="$FS" read -r kind a b c d e f g h i j k; do
    [ "$kind" = product ] || continue
    [ "$first" = true ] || printf ','
    first=false
    printf '{"id":%s,"product":%s,"version":%s,"tls_library":%s,"running":%s,"place":%s,"place_state":%s,"pqc_capable":%s,"pqc_reason":%s' \
      "$(sb_json "$a")" "$(sb_json "$b")" "$(sb_json "$c")" "$(sb_json "$d")" "$([ "$e" = yes ] && echo true || echo false)" "$(sb_json "$f")" "$(sb_json "$g")" "$h" "$(sb_json "$i")"
    for sub in directive listener rating verdict; do
      printf ',"%ss":[' "$sub"
      awk -F "$FS" -v kind="$sub" -v id="$a" '$1 == kind && $2 == id' "$1" | {
        local n=0
        while IFS="$FS" read -r _ _ b c d e f g h i j k; do
          [ "$n" = 0 ] || printf ','
          n=$((n + 1))
          case "$sub" in
            directive) printf '{"where":%s,"part":%s,"scope":%s,"text":%s}' "$(sb_json "$b")" "$(sb_json "$c")" "$(sb_json "$d")" "$(sb_json "$e")" ;;
            listener) printf '{"name":%s,"host":%s,"port":%s,"sni":%s,"measured":%s,"answers":%s,"tls13":%s,"group":%s,"tls12":%s,"older":%s,"accepts_old_cipher":%s}' \
              "$(sb_json "$b")" "$(sb_json "$c")" "$(sb_json "$d")" "$(sb_json "$e")" "$([ "$f" = "not measured" ] && echo false || echo true)" "$([ "$f" = answers ] && echo true || echo false)" \
              "$([ "$g" = yes ] && echo true || echo false)" "$(sb_json "$h")" "$([ "$i" = yes ] && echo true || echo false)" "$(sb_json "$j")" "$([ "$k" = yes ] && echo true || echo false)" ;;
            rating) printf '{"listener":%s,"item":%s,"value":%s,"rating":%s,"why":%s}' "$(sb_json "$b")" "$(sb_json "$c")" "$(sb_json "$d")" "$([ -n "$e" ] && sb_json "$e" || echo null)" "$(sb_json "$f")" ;;
            verdict) printf '{"status":%s,"item":%s,"text":%s,"next":%s}' "$(sb_json "$b")" "$(sb_json "$c")" "$(sb_json "$d")" "$(sb_json "$e")" ;;
          esac
        done
      }
      printf ']'
    done
    printf '}'
  done < "$1"
  printf ']}\n'
}

report_html() {
  local kind a b c d e f g h i j k open=""
  printf '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">\n<title>TLS report: %s</title>\n' "$(html "$(hostname 2>/dev/null || true)")"
  printf '<style>body{font-family:Arial,sans-serif;margin:2rem;color:#1f2328}table{border-collapse:collapse;margin:0 0 1.5rem}td,th{border:1px solid #d0d7de;padding:.35rem .6rem;text-align:left;vertical-align:top}th{background:#f6f8fa}</style></head><body>\n'
  printf '<h1>TLS report: %s</h1>\n<p>%s, <a href="%s">%s</a>. Last start of the server: %s. openssl: %s</p>\n' "$(html "$(hostname 2>/dev/null || true)")" "$(html "$SCRIPT_NAME $SCRIPT_VERSION")" "$PAGE" "$PAGE" "$(html "$(up_since)")" "$(html "$(openssl version 2>/dev/null || true)")"
  while IFS="$FS" read -r kind a b c d e f g h i j k; do
    if [ "$kind" != "$open" ] || [ "$kind" = product ]; then
      [ -z "$open" ] || [ "$open" = product ] || printf '</table>\n'
      case "$kind" in
        directive) printf '<h3>TLS directives of the configuration</h3>\n<table><tr><th>Where</th><th>Part</th><th>Scope</th><th>Directive</th></tr>\n' ;;
        listener) printf '<h3>Sites and listeners</h3>\n<table><tr><th>Site</th><th>Address</th><th>TLS 1.3</th><th>Group</th><th>TLS 1.2</th><th>Older</th><th>Cipher suite outside the profile</th></tr>\n' ;;
        rating) printf '<h3>Rating</h3>\n<p>%s; %s; %s; %s. %s</p>\n<table><tr><th>Site</th><th>Item</th><th>Found</th><th>Rating</th></tr>\n' "$(rating_text good)" "$(rating_text fallback)" "$(html "$(rating_text remove_now)")" "$(rating_text broken)" "$(html "$RATING_FOOTNOTE")" ;;
        verdict) printf '<h3>Verdicts</h3>\n<table><tr><th>Status</th><th>Item</th><th>Finding</th><th>Next step</th></tr>\n' ;;
      esac
      open="$kind"
    fi
    case "$kind" in
      product) printf '<h2>%s %s</h2>\n<p>TLS library: %s. Running: %s. Own place: %s (%s). Post-quantum key exchange: %s.</p>\n' "$(html "$b")" "$(html "$c")" "$(html "$d")" "$(html "$e")" "$(html "${f:-none}")" "$(html "$g")" "$([ "$h" = true ] && echo 'the library can' || html "the library cannot: $i")" ;;
      directive) printf '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n' "$(html "$b")" "$(html "$c")" "$(html "$d")" "$(html "$e")" ;;
      listener) printf '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n' "$(html "$b")" "$(html "$c:$d")" "$(html "${g:-$f}")" "$(html "$h")" "$(html "$i")" "$(html "${j:-no}")" "$(html "$k")" ;;
      rating) printf '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n' "$(html "$b")" "$(html "$c")" "$(html "$d")" "$([ "$c" = note ] || html "$(rating_text "$e")$([ -z "$f" ] || [ "$e" = good ] || echo " ($f)")")" ;;
      verdict) printf '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n' "$(html "$b")" "$(html "$c")" "$(html "$d")" "$(html "$e")" ;;
    esac
  done < "$1"
  [ -z "$open" ] || [ "$open" = product ] || printf '</table>\n'
  printf '</body></html>\n'
}

# ---- Main.

while [ $# -gt 0 ]; do
  case "$1" in
    --apply|--undo)
      [ "$ACTION" = report ] || [ "$ACTION" = "${1#--}" ] || { say "Choose one of --apply and --undo."; exit 3; }
      ACTION="${1#--}" ;;
    --dry-run) DRY_RUN=true ;;
    --force) FORCE=true ;;
    --pqc|--parts|--product|--report|--report-file|--host|--port|--sni|--wait)
      [ $# -ge 2 ] || { say "$1 needs a value. $SCRIPT_NAME --help lists the options."; exit 3; }
      case "$1" in
        --pqc) LEVEL="$2" ;; --parts) PARTS="$2" ;; --product) ONLY_PRODUCT="$2" ;; --report) REPORT="$2" ;;
        --report-file) REPORT_FILE="$2" ;; --host) GIVEN_HOST="$2" ;; --port) GIVEN_PORT="$2" ;; --sni) GIVEN_SNI="$2" ;; --wait) WAIT="$2" ;;
      esac
      shift ;;
    --version) say "$SCRIPT_NAME $SCRIPT_VERSION"; exit 0 ;;
    -h|--help) usage; exit 0 ;;
    *) say "Unknown option $1. $SCRIPT_NAME --help lists the options."; exit 3 ;;
  esac
  shift
done
case "$LEVEL" in ignore|when-possible|only) ;; *) say "--pqc takes ignore, when-possible or only."; exit 3 ;; esac
[[ "$PARTS" =~ ^(protocols|ciphers|groups)(,(protocols|ciphers|groups))*$ ]] || { say "--parts takes protocols, ciphers and groups, separated by commas."; exit 3; }
# Each part once, in the script's order.
PARTS="$(for part in protocols ciphers groups; do [[ ",$PARTS," != *",$part,"* ]] || printf '%s,' "$part"; done)"
PARTS="${PARTS%,}"
case "$ONLY_PRODUCT" in ''|nginx|apache|haproxy) ;; *) say "--product takes nginx, apache or haproxy."; exit 3 ;; esac
case "$REPORT" in text|json|html) ;; *) say "--report takes text, json or html."; exit 3 ;; esac
[[ "$WAIT" =~ ^[0-9]{1,5}$ ]] || { say "--wait takes a number of seconds."; exit 3; }
[[ -z "$GIVEN_PORT" || "$GIVEN_PORT" =~ ^[0-9]{1,5}$ ]] || { say "--port takes a port number."; exit 3; }
[[ -z "$GIVEN_HOST" || "$GIVEN_HOST" =~ ^[A-Za-z0-9:][A-Za-z0-9.:-]{0,252}$ ]] || { say "--host takes a host name or an IP address."; exit 3; }
[[ -z "$GIVEN_SNI" || "$GIVEN_SNI" =~ ^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$ ]] || { say "--sni takes a host name."; exit 3; }
# The level without post-quantum key exchange leaves the groups alone, whatever --parts says.
[ "$LEVEL" != ignore ] || { PARTS=",$PARTS,"; PARTS="${PARTS//,groups,/,}"; PARTS="${PARTS#,}"; PARTS="${PARTS%,}"; }
[ -n "$PARTS" ] || { say "--pqc ignore with --parts groups leaves nothing to set."; exit 3; }
[ -z "$ONLY_PRODUCT" ] || PRODUCTS="$ONLY_PRODUCT"

if [ "$ACTION" = report ]; then
  # A directory of the report's own: nothing in it has a name another user could have made first.
  REPORT_DIR="$(mktemp -d "${TMPDIR:-/tmp}/sslbrain-tls-report.XXXXXXXX")" || { say "No temporary directory could be made in ${TMPDIR:-/tmp}."; exit 1; }
  trap 'rm -rf -- "$REPORT_DIR"' EXIT
  REPORT_TMP="$REPORT_DIR/records"
  for PRODUCT in $PRODUCTS; do
    ( "load_$PRODUCT"; report_product ) >> "$REPORT_TMP" || true
  done
  if [ -n "$REPORT_FILE" ]; then
    "report_$REPORT" "$REPORT_TMP" > "$REPORT_FILE"
    say "The report is in $REPORT_FILE"
  else
    "report_$REPORT" "$REPORT_TMP"
  fi
  exit 0
fi

if [ "$(id -u)" != 0 ] && { [ "$ACTION" = undo ] || [ "$DRY_RUN" != true ]; }; then
  say "Run as root: changing the server's configuration needs it."
  exit 3
fi
command -v openssl >/dev/null 2>&1 || { say "openssl is not installed: the script checks each change with a TLS handshake. Nothing was changed."; exit 3; }
say "$SCRIPT_NAME $SCRIPT_VERSION$([ "$ACTION" != apply ] || echo ": Mozilla intermediate, post-quantum key exchange $LEVEL, parts $PARTS")"
if [ "$DRY_RUN" != true ]; then lock_run; fi
if [ "$ACTION" = undo ]; then state_trusted || exit 1; fi
worst=0
found=false
for PRODUCT in $PRODUCTS; do
  status=0
  if [ "$ACTION" = apply ]; then
    ( "load_$PRODUCT"; tlsset_detect >/dev/null 2>&1 || [ "${TLSSET_FAIL_CODE:-}" != not_installed ] ) || continue
    found=true
    ( "load_$PRODUCT"; apply_product ) || status=$?
  else
    [ -f "$STATE_DIR/$PRODUCT.before" ] || continue
    found=true
    ( "load_$PRODUCT"; undo_product ) || status=$?
  fi
  # A failure (1) counts over a refusal (2).
  case "$status" in 0) ;; 1) worst=1 ;; *) [ "$worst" = 1 ] || worst="$status" ;; esac
done
if [ "$found" != true ]; then
  if [ "$ACTION" = undo ]; then say "Nothing to undo: the script has changed nothing on this server that is not already put back."; exit 0; fi
  say "No nginx, Apache httpd or HAProxy was found on this server."
  exit 3
fi
exit "$worst"
