#!/bin/bash
# Copyright 2026 FairSSL A/S - fairssl.dk, fairssl.se, sslbrain.com
# File and guide: https://sslbrain.com/scripts/fortigate-linux/
# Installs on: FortiGate
#
# 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
#   Installs the certificate that lego keeps on this server on a FortiGate, over SSH, and keeps trying until it is
#   installed. Reports every result when it has a report address.
# .DESCRIPTION
#   Used by FairSSL's guide "FortiGate Legacy (Linux Agent)" and, with any ACME service, as lego's deploy hook.
#
#   fairssl-fortigate setup  --name NAME --host ADDRESS [--port 22] [--user admin] [--report-url URL]
#       Asks for the FortiGate password and keeps it in /etc/fairssl-fortigate/NAME.password (root only, 0600),
#       pins FortiGate's SSH host key in /etc/fairssl-fortigate/known_hosts, logs in once and shows what it found.
#   fairssl-fortigate deploy NAME   Installs the certificate now and shows the result. If the attempt fails, a
#                                   background worker keeps trying; deploy again ends its wait for the next attempt.
#   fairssl-fortigate hook NAME     lego's --deploy-hook: ends a waiting worker's wait, starts the worker, returns.
#   fairssl-fortigate resume NAME   At boot: starts the worker again when a restart interrupted a deployment.
#   fairssl-fortigate status NAME   Shows the settings (never the password), the last result and the log.
#
# What the worker does, each attempt: it reads the certificate and key lego saved, logs in to FortiGate with the password
# from the root-only file (handed to ssh by this script as its askpass program, never in a command line, the environment
# or a log), offers its CA store the intermediates (after a restart FortiGate serves only those), uploads the certificate
# with them as a local certificate named fssl-<6 hex of the certificate name>-<12 hex of the certificate's SHA-256>,
# points SSL VPN and/or admin HTTPS at it and reads FortiGate's full settings back, every 5 seconds for up to 30 seconds;
# a change FortiGate does not show yet is not an error, and the log says when it is checked again. A TLS handshake shows
# what the listener serves, for the log only: the configuration read over SSH decides, and only a listener that answered
# before the change and gives no handshake after it gets its previous certificate back (ROLLED_BACK; ROLLBACK_FAILED when
# FortiGate did not take it back). It keeps the previous certificate object and deletes older objects of its own. A
# failed attempt is tried again after 1, 2, 5, 10, 30 and then every 60 minutes (a failure that waits for the customer
# once a day: NO_ROLE, ROLLED_BACK, ROLLBACK_FAILED, CFG_SAVE_REVERT), for as long as it takes, also after a restart of
# this server and with a newer version of this script once that is installed. Every attempt is reported to the report address, with
# the same failure codes as FairSSL's Windows script Deploy-FortiGate.ps1; it counts as failed only when the certificate
# is still not installed 15 minutes after the first failed attempt (those that wait for the customer at once; an
# unchanged failure once a day). A report the receiver has not confirmed waits in /var/lib/fairssl-fortigate/NAME.outbox and
# is sent again; one it refuses is moved to its folder 'refused'.
#
# Which FortiGate certificate settings it changes, without options: a setting that already uses this certificate
# name's object, or a certificate for the same name (its common name is the new certificate's common name or one of
# its DNS names; the object of FairSSL's earlier script is taken over and cleaned up by that rule too); on a
# FortiGate without VDOMs, SSL VPN when it uses a factory certificate (Fortinet_Factory, self-sign, ...) and listens
# on an interface, and admin HTTPS when it uses a factory certificate and SSL VPN is not in use. It never replaces a
# certificate of another name that you chose. On the secondary unit of an HA cluster it changes nothing
# (HA_SECONDARY). With cfg-save manual it saves the configuration after a change and reports a save FortiGate
# refuses (CFG_SAVE_FAILED: only super_admin may save); with cfg-save revert it changes nothing (CFG_SAVE_REVERT).
#
# A FortiGate with multiple VDOMs needs no option: a VDOM administrator works in its own VDOM (certificate, CA store,
# SSL VPN, which gets the certificate whatever it used); admin HTTPS is global and FortiGate does not let it change
# that, so admin HTTPS is left as it is and the log and the report say so. A global administrator's worker reads SSL
# VPN in every VDOM and moves it where it uses this certificate or a certificate for the same name; it takes over no
# factory certificate on SSL VPN, as each VDOM may be another customer's. Its certificate is uploaded once in global,
# because admin HTTPS can only use a global certificate, and every VDOM uses that object. The administrator of
# several VDOMs without global access works inside 'config vdom' in the VDOM FortiGate starts it in, the only one it
# shows, and there only where SSL VPN uses this certificate or a certificate for the same name. An admin profile that
# is refused 'get system status' (read-write on System and VPN, cli-get/show/config) is recognised by the scopes it
# is let into; its HA role comes from 'get system ha status'. An account FortiGate shows neither its status nor its
# global settings changes only this certificate's object or a certificate for the same name.
#
# Requires: bash 4, OpenSSH client, openssl, curl, flock and setsid (util-linux), run as root.
# .PARAMETER --name
#   setup: the certificate's name, as lego knows it (--cert.name). The other commands take it as NAME.
# .PARAMETER --host
#   setup: FortiGate's IP address or host name.
# .PARAMETER --port
#   setup: FortiGate's SSH port. Defaults to 22.
# .PARAMETER --user
#   setup: the FortiGate administrator the script logs in as. Defaults to admin.
# .PARAMETER --report-url
#   setup: where each result is reported, an https address. Leave it out: the address set up before is kept,
#   otherwise DEFAULT_REPORT_URL below is used; when that is empty too, nothing is sent.
# .PARAMETER --lego-path
#   setup: lego's --path. Defaults to /etc/ssl/fortigate.

# Where each result is reported: an https address. Empty: nothing is sent. setup's --report-url replaces it for
# one certificate. FairSSL's guide gives FairSSL's address with --report-url.
DEFAULT_REPORT_URL=""

umask 077

# An askpass call from ssh: answer with the password from the root-only file, nothing else.
if [ -n "${FAIRSSL_FORTIGATE_ASKPASS_FILE:-}" ]; then
    cat -- "$FAIRSSL_FORTIGATE_ASKPASS_FILE"
    exit
fi

SCRIPT_VERSION="1.5.0"
PATH="${PATH:+$PATH:}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export LC_ALL=C

SELF=$(readlink -f -- "$0")
CONFIG_DIR=${FAIRSSL_FORTIGATE_CONFIG_DIR:-/etc/fairssl-fortigate}
STATE_DIR=${FAIRSSL_FORTIGATE_STATE_DIR:-/var/lib/fairssl-fortigate}
LOG_DIR=${FAIRSSL_FORTIGATE_LOG_DIR:-/var/log/fairssl-fortigate}
KNOWN_HOSTS="$CONFIG_DIR/known_hosts"
# Reports the receiver has not confirmed wait in $STATE_DIR/NAME.outbox (set_outbox). Version 1.3.0 and earlier kept the
# reports of every name in one folder; what still waits there is sent too.
OUTBOX=""
OLD_OUTBOX="$STATE_DIR/outbox"
OLD_SCRIPT=/usr/local/bin/fairssl-fortigate-deploy.sh

# A limit only notices something that has stopped: ssh output silent this long, a TLS handshake or a report
# that has not finished in this long.
SILENCE_LIMIT=${FAIRSSL_FORTIGATE_SILENCE_LIMIT:-300}
# Waits between attempts in seconds; the last one repeats with no end.
read -r -a RETRY_WAITS <<< "${FAIRSSL_FORTIGATE_RETRY_WAITS:-60 120 300 600 1800 3600}"
# How long FortiGate gets to start serving a newly bound certificate (measured: 5-20 seconds).
SWITCH_WAIT=${FAIRSSL_FORTIGATE_SWITCH_WAIT:-300}
SWITCH_POLL=${FAIRSSL_FORTIGATE_SWITCH_POLL:-10}
# A change FortiGate accepted is read back every 5 seconds for up to 30 (owner 20-11-2026).
READBACK_WAIT=${FAIRSSL_FORTIGATE_READBACK_WAIT:-30}
READBACK_POLL=${FAIRSSL_FORTIGATE_READBACK_POLL:-5}
# FairSSL hears of a failure only when the certificate has failed for this long (owner 20-11-2026).
FAILURE_AFTER=${FAIRSSL_FORTIGATE_FAILURE_AFTER:-900}
# NO_ROLE, ROLLED_BACK, ROLLBACK_FAILED and CFG_SAVE_REVERT wait for the customer's step: tried once a day.
NO_ROLE_WAIT=${FAIRSSL_FORTIGATE_NO_ROLE_WAIT:-86400}

FOREGROUND=0
NAME=""
LOG=/dev/null
WORK=""
ROLES=()
CA_RESULTS=()

say() { printf '%s\n' "$*"; }
# The FortiGate password of the settings in use (load_config). Every log line, failure text and report goes through
# redact, so neither the password nor a PEM block gets there when FortiGate or ssh repeats it in an answer.
SECRET=""
redact() {
    local text=$1 rest
    [ -n "$SECRET" ] && text=${text//"$SECRET"/[password]}
    while [[ $text == *-----BEGIN* ]]; do
        rest=${text#*-----BEGIN}
        if [[ $rest == *-----END*-----* ]]; then rest=${rest#*-----END}; rest=${rest#*-----}; else rest=""; fi
        text="${text%%-----BEGIN*}[PEM removed]$rest"
    done
    printf '%s' "$text"
}
log() {
    local text line
    text=$(redact "$*")
    line="$(date -u +%Y-%m-%dT%H:%M:%SZ) $text"
    printf '%s\n' "$line" >> "$LOG"
    if [ -n "$WORK" ]; then printf '%s\n' "$line" >> "$WORK/attempt.log"; fi
    if [ "$FOREGROUND" = 1 ]; then printf '%s\n' "$text"; fi
}
die() { printf 'fairssl-fortigate: %s\n' "$*" >&2; exit 1; }

valid_name() { [[ $1 =~ ^[A-Za-z0-9_@-][A-Za-z0-9_.@-]*$ ]] && [ ${#1} -le 200 ]; }

require_root() { [ "$(id -u)" = 0 ] || die "run it as root (sudo)."; }

# ---------------------------------------------------------------------------------------------------------------
# Settings: KEY=value lines, read without running them as shell code.
# ---------------------------------------------------------------------------------------------------------------
config_file() { printf '%s/%s.conf' "$CONFIG_DIR" "$1"; }
password_file() { printf '%s/%s.password' "$CONFIG_DIR" "$1"; }

load_config() {
    local file key value
    file=$(config_file "$NAME")
    [ -r "$file" ] || return 1
    FGT_HOST="" FGT_PORT=22 FGT_USER="" RENEWAL_ID="" REPORT_URL="" LEGO_PATH=/etc/ssl/fortigate REPORT_PROXY=""
    while IFS='=' read -r key value; do
        case "$key" in
            FGT_HOST) FGT_HOST=$value ;;
            FGT_PORT) FGT_PORT=$value ;;
            FGT_USER) FGT_USER=$value ;;
            RENEWAL_ID) RENEWAL_ID=$value ;;
            REPORT_URL) REPORT_URL=$value ;;
            LEGO_PATH) LEGO_PATH=$value ;;
            REPORT_PROXY) REPORT_PROXY=$value ;;
        esac
    done < "$file"
    [ -n "$REPORT_URL" ] || REPORT_URL=$DEFAULT_REPORT_URL
    # Only an https address is used; anything else is no address.
    case $REPORT_URL in https://*) ;; *) REPORT_URL="" ;; esac
    PASSWORD_FILE=$(password_file "$NAME")
    OUTBOX="$STATE_DIR/$NAME.outbox"
    [ -n "$FGT_HOST" ] && [ -n "$FGT_USER" ] && [ -r "$PASSWORD_FILE" ] || return 1
    SECRET=$(cat -- "$PASSWORD_FILE")
}

open_log() {
    OUTBOX="$STATE_DIR/$NAME.outbox"
    mkdir -p "$LOG_DIR" "$STATE_DIR" "$OUTBOX"
    chmod 0700 "$LOG_DIR" "$STATE_DIR" "$OUTBOX"
    LOG="$LOG_DIR/$NAME.log"
    rotate_log
}

# Kept small: the newest megabyte, plus the one before it. Checked at the start of every attempt.
rotate_log() {
    if [ -f "$LOG" ] && [ "$(wc -c < "$LOG")" -gt 1048576 ]; then mv -f "$LOG" "$LOG.1"; fi
    touch "$LOG"
}

new_work_dir() {
    [ -n "$WORK" ] && rm -rf "$WORK"
    WORK=$(mktemp -d "${TMPDIR:-/tmp}/fairssl-fortigate.XXXXXX") || die "cannot create a temporary folder"
}
cleanup_work() { [ -n "$WORK" ] && rm -rf "$WORK"; }
trap cleanup_work EXIT

# ---------------------------------------------------------------------------------------------------------------
# SSH to FortiGate. FortiOS answers a refused command with text and exit code 0 (measured on 7.4.13), so every
# result is read back from FortiGate's state, and FortiGate's own words are only used to explain a failure.
# ---------------------------------------------------------------------------------------------------------------
FAIL_CODE=""
FAIL_TEXT=""
fail() { FAIL_CODE=$1; FAIL_TEXT=$(redact "$2"); log "$1: $2"; return 1; }

# Older FortiOS (6.x) signs its host key only with SHA-1 ("ssh-rsa"), which OpenSSH refuses since 8.8 unless asked.
# OpenSSH before 7.0 does not know the "+" form; ssh -G only reads the options, it connects nowhere.
host_key_options() {
    HOSTKEY_PROBED=1
    HOSTKEY_OPTIONS=()
    if ssh -G -o HostKeyAlgorithms=+ssh-rsa localhost > /dev/null 2>&1 < /dev/null; then
        HOSTKEY_OPTIONS=(-o HostKeyAlgorithms=+ssh-rsa)
    fi
}

# Runs the FortiOS commands in file $1. stdout lands in $WORK/out, stderr in $WORK/err. Stops ssh only when it
# has printed nothing for SILENCE_LIMIT seconds.
fgt() {
    [ -n "${HOSTKEY_PROBED:-}" ] || host_key_options
    local batch=$1 pid start now size last=-1 quiet_since rc
    : > "$WORK/out"
    : > "$WORK/err"
    # setsid: without a terminal, every OpenSSH version takes the password from the askpass program.
    SSH_ASKPASS="$SELF" SSH_ASKPASS_REQUIRE=force DISPLAY="${DISPLAY:-fairssl-fortigate}" \
        FAIRSSL_FORTIGATE_ASKPASS_FILE="$PASSWORD_FILE" \
        setsid ssh -T -p "$FGT_PORT" \
        -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$KNOWN_HOSTS" -o GlobalKnownHostsFile=/dev/null \
        "${HOSTKEY_OPTIONS[@]}" \
        -o PubkeyAuthentication=no -o PreferredAuthentications=keyboard-interactive,password \
        -o NumberOfPasswordPrompts=1 -o ConnectTimeout="$SILENCE_LIMIT" \
        -o ServerAliveInterval=30 -o ServerAliveCountMax=10 -o LogLevel=ERROR \
        -- "$FGT_USER@$FGT_HOST" < "$batch" > "$WORK/out" 2> "$WORK/err" &
    pid=$!
    start=$(date +%s)
    quiet_since=$start
    while kill -0 "$pid" 2>/dev/null; do
        sleep 0.2
        now=$(date +%s)
        size=$(( $(wc -c < "$WORK/out") + $(wc -c < "$WORK/err") ))
        if [ "$size" != "$last" ]; then last=$size; quiet_since=$now; fi
        if [ $((now - quiet_since)) -ge "$SILENCE_LIMIT" ]; then
            kill "$pid" 2>/dev/null
            wait "$pid" 2>/dev/null
            fail FORTIGATE_SILENT "FortiGate $FGT_HOST:$FGT_PORT sent nothing for $SILENCE_LIMIT seconds"
            return 1
        fi
    done
    wait "$pid"
    rc=$?
    [ "$rc" = 0 ] && return 0
    ssh_failure "$rc"
}

ssh_failure() {
    local err
    err=$(redact "$(tr -d '\r' < "$WORK/err")" | grep -v '^$' | head -n 3 | tr '\n' ' ')
    case "$err" in
        *"REMOTE HOST IDENTIFICATION HAS CHANGED"*|*"Host key verification failed"*)
            if ssh-keygen -F "$(known_hosts_key)" -f "$KNOWN_HOSTS" > /dev/null 2>&1; then
                fail HOSTKEY_CHANGED "FortiGate $FGT_HOST:$FGT_PORT answered with another SSH host key than the one pinned at setup. If FortiGate was replaced or reinstalled, run: sudo fairssl-fortigate setup --name $NAME --host $FGT_HOST --port $FGT_PORT --user $FGT_USER"
            else
                fail HOSTKEY_UNKNOWN "no SSH host key is pinned for $FGT_HOST:$FGT_PORT; run fairssl-fortigate setup again"
            fi ;;
        *"no matching host key type found"*)
            # The script asks for ssh-rsa (host_key_options); RHEL, Rocky and Alma 9 still refuse it in their system
            # policy (measured on Rocky 9).
            fail HOSTKEY_TYPE "FortiGate $FGT_HOST:$FGT_PORT signs its SSH host key only with SHA-1 (ssh-rsa), and this server's system policy refuses that ($err). Update FortiOS, or on RHEL, Rocky or Alma 9 allow it with: sudo update-crypto-policies --set DEFAULT:SHA1" ;;
        *"Permission denied"*|*"Authentication failed"*|*"Too many authentication failures"*)
            fail AUTH_FAILED "FortiGate refused the login of '$FGT_USER'. If the password was changed, run fairssl-fortigate setup again" ;;
        *"timed out"*|*"No route to host"*|*"Connection refused"*|*"Network is unreachable"*|*"Could not resolve"*|*"Name or service not known"*|*"Connection reset"*|*"closed by remote host"*)
            fail CONNECT_FAILED "no SSH connection to FortiGate on $FGT_HOST:$FGT_PORT ($err)" ;;
        *)
            fail CONNECT_FAILED "ssh to FortiGate on $FGT_HOST:$FGT_PORT ended with exit code $1 ($err)" ;;
    esac
}

known_hosts_key() {
    if [ "$FGT_PORT" = 22 ]; then printf '%s' "$FGT_HOST"; else printf '[%s]:%s' "$FGT_HOST" "$FGT_PORT"; fi
}

# FortiGate's answer, for the log: refusals and errors only, and nothing that could be key material. The password is
# taken out of the whole answer first (the shaping below could cut it into pieces). Then, line by line: a line of a
# PEM block's frame goes, and every run of 16 or more base64 characters, wherever in a line FortiGate repeats it, as
# in Deploy-FortiGate.ps1. FortiOS 7.4.13 itself echoes only ">" for each line of a PEM it is given; that echo goes
# too, and so do the lines FortiGate greets every login with after an unclean restart.
fgt_answer() {
    local text
    text=$(cat "$WORK/err" "$WORK/out" | tr -d '\r')
    [ -n "$SECRET" ] && text=${text//"$SECRET"/[password]}
    printf '%s\n' "$text" \
        | grep -E 'Command fail|Return code|error|Error|invalid|Invalid|not |duplicated|Unknown action|MUST|too long|denied|fail|used' \
        | grep -v -E 'PRIVATE|BEGIN|END' | sed -E 's/^.*[#$] //; s/^(> ?)+//; s#[A-Za-z0-9+/]{16,}={0,2}"?##g' \
        | grep -v -E '^(WARNING: File System|It is strongly|Please run|Note: The device)' \
        | grep -v -E '^[[:space:]]*$' | sort -u | head -n 8 | tr '\n' ' '
}

# The value of "key : value" in a FortiOS "get" output.
fgt_value() {
    tr -d '\r' < "$WORK/out" | sed -E 's/^([^ ]+ (\([^)]*\) )?[#$] )+//' \
        | awk -v k="$1" '{ line=$0; sub(/^[ \t]+/, "", line) }
            index(line, k) == 1 { rest = substr(line, length(k) + 1); if (rest ~ /^[ \t]*:/) { sub(/^[ \t]*:[ \t]*/, "", rest); sub(/[ \t]+$/, "", rest); gsub(/^"|"$/, "", rest); print rest; exit } }'
}

fgt_refused() { grep -q -i -E 'Command fail|parse error|Unknown action|invalid command|unknown command|Permission denied' "$WORK/out" "$WORK/err"; }

# The names in a FortiOS list ("== [ name ]"), one per line.
fgt_names() { tr -d '\r' < "$WORK/out" | sed -n -E 's/^.*== \[ (.*) \][[:space:]]*$/\1/p'; }

# Multiple VDOMs: a global administrator runs VDOM commands inside 'config vdom' / 'edit <vdom>' (the session's own
# VDOM unless $1 names another) and global ones inside 'config global'. The administrator of one VDOM already stands
# in it, and a FortiGate without VDOMs has neither scope. The administrator of several VDOMs (VDOM_SCOPED) starts at
# the top, where a VDOM command is refused, and works inside 'config vdom' / 'edit <vdom>' too (FortiOS 7.4.13,
# measured). Both read the commands on stdin.
global_admin_on_vdoms() { [ "${MULTI_VDOM:-0}" = 1 ] && [ "${VDOM_ADMIN:-0}" = 0 ]; }
vdom_scoped() { global_admin_on_vdoms || [ "${VDOM_SCOPED:-0}" = 1 ]; }
in_vdom() {
    if vdom_scoped; then printf 'config vdom\nedit "%s"\n' "${1:-$HOME_VDOM}"; cat; printf 'end\n'; else cat; fi
}
in_global() {
    if global_admin_on_vdoms; then printf 'config global\n'; cat; printf 'end\n'; else cat; fi
}

comma_list() { local list; list=$(printf '%s, ' "$@"); printf '%s' "${list%, }"; }

# ---------------------------------------------------------------------------------------------------------------
# The certificate on disk.
# ---------------------------------------------------------------------------------------------------------------
read_certificate() {
    local bundle=$LEGO_PATH/certificates/$NAME.crt key=$LEGO_PATH/certificates/$NAME.key i san
    LEAF_FP="" LEAF_SHA1="" LEAF_CN="" LEAF_EXPIRY="" LEAF_KEY_TYPE="" LEAF_NAMES=()
    if [ ! -s "$bundle" ] || [ ! -s "$key" ]; then
        fail PEM_MISSING "lego's certificate $bundle or its key is missing; run the lego command from the guide"
        return 1
    fi
    KEY_FILE=$key
    split_pem pem < "$bundle"
    LEAF_FILE="$WORK/pem-01.crt"
    if [ ! -s "$LEAF_FILE" ] || ! openssl x509 -in "$LEAF_FILE" -noout 2>/dev/null; then
        fail PEM_MISSING "$bundle holds no readable certificate"
        return 1
    fi
    LEAF_FP=$(cert_sha256 "$LEAF_FILE")
    # The name, thumbprint and expiry go into every report, also when the certificate is not installed (expired, wrong
    # key type): FairSSL needs them to tell whose failure it is, and refuses a report without a domain.
    LEAF_SHA1=$(openssl x509 -in "$LEAF_FILE" -noout -fingerprint -sha1 | sed 's/.*=//; s/://g' | tr 'a-f' 'A-F')
    while IFS= read -r san; do [ -n "$san" ] && LEAF_NAMES+=("$san"); done < <(openssl x509 -in "$LEAF_FILE" -noout -text \
        | grep -o 'DNS:[^,]*' | sed 's/^DNS://; s/[[:space:]]*$//')
    LEAF_CN=$(openssl x509 -in "$LEAF_FILE" -noout -subject -nameopt RFC2253 | sed -n 's/^subject=//; s/\\,/%2C/g; s/.*CN=\([^,]*\).*/\1/p')
    if [ -z "$LEAF_CN" ] || [[ $LEAF_CN == subject* ]]; then LEAF_CN=${LEAF_NAMES[0]:-}; fi
    LEAF_EXPIRY=$(date -u -d "$(openssl x509 -in "$LEAF_FILE" -noout -enddate | sed 's/^notAfter=//')" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null)
    # FortiGate takes an expired certificate, one that is not valid yet and an Ed25519 one, and serves them (sslbrain
    # agent test on 7.4.13, 12-11-2026); browsers refuse all three. A certificate fresh from the CA looks not valid yet
    # on a server whose clock is behind, so only one more than a day ahead is held back, and tried again until it is valid.
    local key_type not_before
    key_type=$(openssl x509 -in "$LEAF_FILE" -noout -text | sed -n 's/^[[:space:]]*Public Key Algorithm:[[:space:]]*//p' | head -n 1)
    LEAF_KEY_TYPE=$(key_type_name "$key_type")
    if ! openssl x509 -in "$LEAF_FILE" -noout -checkend 0 > /dev/null; then
        fail CERTIFICATE_EXPIRED "the certificate in $bundle expired on $(openssl x509 -in "$LEAF_FILE" -noout -enddate | sed 's/^notAfter=//'); it is not installed, because browsers refuse it. lego's next renewal brings a new one"
        return 1
    fi
    case $key_type in
        rsaEncryption|id-ecPublicKey) ;;
        *)
            fail KEY_TYPE "the certificate in $bundle has a ${key_type:-unknown} key; it is not installed, because browsers use only RSA and ECDSA server certificates. Issue it again with lego's --key-type rsa2048 or ec256"
            return 1 ;;
    esac
    not_before=$(date -u -d "$(openssl x509 -in "$LEAF_FILE" -noout -startdate | sed 's/^notBefore=//')" +%s 2> /dev/null) || not_before=0
    if [ "$not_before" -gt $(( $(date +%s) + 86400 )) ]; then
        fail CERTIFICATE_NOT_YET_VALID "the certificate in $bundle is valid from $(date -u -d "@$not_before" +%Y-%m-%dT%H:%M:%SZ), and this server's clock says $(date -u +%Y-%m-%dT%H:%M:%SZ); it is installed once it is valid. If the clock is wrong, correct it"
        return 1
    fi
    # The chain goes up in the order the CA gave it, each certificate once. A copy of the leaf, a repeated
    # intermediate and a self-signed root are left out: clients hold their roots, and a cross-signed
    # intermediate is not self-signed, so it stays.
    CHAIN_FILES=()
    local fp seen=" $LEAF_FP "
    for i in "$WORK"/pem-*.crt; do
        [ "$i" = "$LEAF_FILE" ] && continue
        fp=$(cert_sha256 "$i")
        [[ $seen == *" $fp "* ]] && continue
        seen="$seen$fp "
        [ "$(openssl x509 -in "$i" -noout -subject_hash)" = "$(openssl x509 -in "$i" -noout -issuer_hash)" ] && continue
        CHAIN_FILES+=("$i")
    done
    OBJECT="fssl-$(id6)-${LEAF_FP:0:12}"
    return 0
}

# "RSA 2048", "ECDSA P-256", or the algorithm's own name, for the report: read from the certificate's public key.
key_type_name() {
    local text bits curve
    text=$(openssl x509 -in "$LEAF_FILE" -noout -text 2> /dev/null)
    bits=$(sed -n 's/^.*Public-Key: (\([0-9]*\) bit).*$/\1/p' <<< "$text" | head -n 1)
    case $1 in
        rsaEncryption) printf 'RSA%s' "${bits:+ $bits}" ;;
        id-ecPublicKey)
            curve=$(sed -n 's/^[[:space:]]*NIST CURVE:[[:space:]]*//p' <<< "$text" | head -n 1)
            [ -n "$curve" ] || curve=$(sed -n 's/^[[:space:]]*ASN1 OID:[[:space:]]*//p' <<< "$text" | head -n 1)
            printf 'ECDSA%s' "${curve:+ $curve}" ;;
        *) printf '%s' "$1" ;;
    esac
}

# Splits the PEM certificates on stdin into $WORK/<prefix>-01.crt, -02.crt, ... in their order.
split_pem() {
    rm -f "$WORK/$1"-*.crt
    awk -v base="$WORK/$1" '/-----BEGIN CERTIFICATE-----/ { n++; file = sprintf("%s-%02d.crt", base, n) }
        file { print > file } /-----END CERTIFICATE-----/ { close(file); file = "" }'
}
cert_sha256() { openssl x509 -in "$1" -noout -fingerprint -sha256 | sed 's/.*=//; s/://g' | tr 'A-F' 'a-f'; }
# True when the fingerprint FortiGate shows for an object is this certificate's: FortiOS 7.4 prints the SHA-256, an
# older release may print the SHA-1.
holds_leaf() { [ -n "$1" ] && { [ "$1" = "$LEAF_FP" ] || [ "$1" = "${LEAF_SHA1,,}" ]; }; }
id6() { printf '%s' "$NAME" | sha256sum | cut -c1-6; }

# Names this script owns on FortiGate: its own, both made from the certificate name given at setup.
own_object() {
    [[ $1 =~ ^fssl-$(id6)-[0-9a-f]{12}$ ]] && return 0
    [ "$1" = "fssl-$(printf '%s' "$NAME" | sha256sum | cut -c1-12)" ] && return 0
    return 1
}
# The name FairSSL's earlier deploy script used: fairssl-acme-<common name without "*.">. example.com and
# *.example.com share it, so such an object is this certificate's only when its common name is one of this
# certificate's names (same_name), as Deploy-FortiGate.ps1 treats the names of its earlier versions.
legacy_object() { [ -n "${LEAF_CN:-}" ] && [ "$1" = "fairssl-acme-${LEAF_CN#\*.}" ]; }
factory_object() { [[ $1 =~ ^(Fortinet_|self-sign$) ]] || [ -z "$1" ]; }
# A certificate for the same name: its common name $1 is the new certificate's common name or one of its DNS names,
# letter for letter in any case (a wildcard only matches the same wildcard). FortiOS shows the subject of a local
# certificate, not its subjectAltName, so the other names of the current certificate cannot be compared (7.4.13).
same_name() {
    local cn=${1,,} name
    [ -n "$cn" ] || return 1
    for name in "$LEAF_CN" "${LEAF_NAMES[@]}"; do [ "${name,,}" = "$cn" ] && return 0; done
    return 1
}

# ---------------------------------------------------------------------------------------------------------------
# What FortiGate has now.
# ---------------------------------------------------------------------------------------------------------------
# SSL VPN per VDOM, keyed by vkey: the VDOM's name, or "#" on a FortiGate without VDOMs.
declare -A VPN_CERT_OF=() VPN_PORT_OF=() VPN_ON_OF=() VPN_IN_USE_OF=() VPN_CN_OF=() VPN_FP_OF=()
vkey() { printf '%s' "${1:-#}"; }
vpn_label() { if [ -n "$1" ]; then printf "SSL VPN in VDOM '%s'" "$1"; else printf 'SSL VPN'; fi; }

detect() {
    local ha status_read=0 mode
    log "Connecting to FortiGate $FGT_HOST port $FGT_PORT as $FGT_USER"
    printf 'get system status\n' > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    if grep -q 'Unknown action' "$WORK/out" "$WORK/err" && ! grep -q 'Version' "$WORK/out"; then
        fail NO_ACCESS "the FortiGate account '$FGT_USER' may not run CLI commands; its admin profile needs cli-get, cli-show and cli-config"
        return 1
    fi
    FGT_VERSION=$(fgt_value Version)
    [ -n "$FGT_VERSION" ] && status_read=1
    # 'FortiGate-VM64-KVM v7.4.13,build2933,260929 (GA.M)' is model FortiGate-VM64-KVM and FortiOS 7.4.13.
    DEVICE_MODEL="" DEVICE_VERSION="" HA_MODE=""
    if [[ $FGT_VERSION =~ ^([^[:space:]]+)[[:space:]]+v([0-9]+(\.[0-9]+)+) ]]; then
        DEVICE_MODEL=${BASH_REMATCH[1]} DEVICE_VERSION="FortiOS ${BASH_REMATCH[2]}"
    fi
    mode=$(fgt_value 'Virtual domain configuration')
    ha=$(fgt_value 'Current HA mode')
    MULTI_VDOM=0 VDOM_ADMIN=0 VDOM_SCOPED=0 SCOPE_GUESSED=0 HOME_VDOM="" ADMIN_NOTE="" CFG_NOTE=""
    VDOMS=("")
    if [ "$status_read" = 0 ] || [ "$mode" = multiple ]; then
        HOME_VDOM=$(fgt_value 'Current virtual domain')
        detect_scope "$status_read" || return 1
    fi
    if [ "$status_read" = 0 ] && [ "$VDOM_ADMIN" = 0 ]; then
        # An admin profile refused 'get system status' (measured on 7.4.13): the HA role from 'get system ha status'.
        printf 'get system ha status\n' | in_global > "$WORK/batch"
        fgt "$WORK/batch" || return 1
        ha=$(ha_role)
        DEVICE_MODEL=$(fgt_value Model)
    fi
    HA_MODE=$ha
    if [[ ${ha,,} =~ (backup|secondary|slave) ]]; then
        fail HA_SECONDARY "$FGT_HOST is the secondary unit of an HA cluster ($ha), and the cluster gives it the primary's configuration, so nothing was changed. Give the cluster's address (the primary unit) to fairssl-fortigate setup and run deploy again"
        return 1
    fi

    ADMIN_CERT="" ADMIN_PORT="" CFG_SAVE=""
    if [ "$VDOM_ADMIN" = 0 ]; then
        printf 'get system global\n' | in_global > "$WORK/batch"
        fgt "$WORK/batch" || return 1
        if fgt_refused; then
            ADMIN_NOTE="left as it is: FortiGate does not show '$FGT_USER' the global settings"
        else
            ADMIN_CERT=$(fgt_value admin-server-cert)
            ADMIN_PORT=$(fgt_value admin-sport)
            CFG_SAVE=$(fgt_value cfg-save)
        fi
    else
        # Admin HTTPS and cfg-save are global; FortiGate refuses a VDOM administrator both, and shows it no sign of
        # cfg-save manual or revert (measured on 7.4.13).
        if [ "$VDOM_SCOPED" = 1 ]; then
            ADMIN_NOTE="left as it is: admin HTTPS is global, and FortiGate does not let '$FGT_USER', an administrator of several VDOMs, change it"
        else
            ADMIN_NOTE="left as it is: admin HTTPS is global, and FortiGate does not let '$FGT_USER', an administrator of VDOM '$HOME_VDOM', change it"
        fi
        CFG_NOTE="not readable with this account: a global administrator saves the configuration when cfg-save is manual"
    fi
    : "${ADMIN_PORT:=443}"

    VPN_CERT_OF=() VPN_PORT_OF=() VPN_ON_OF=() VPN_IN_USE_OF=() VPN_CN_OF=() VPN_FP_OF=()
    for name in "${VDOMS[@]}"; do read_ssl_vpn "$name" || return 1; done

    inventory || return 1
    local vpn_text="" key
    for name in "${VDOMS[@]}"; do
        key=$(vkey "$name")
        [ "${VPN_ON_OF[$key]:-0}" = 1 ] || continue
        vpn_text="$vpn_text; $(vpn_label "$name"): $( [ "${VPN_IN_USE_OF[$key]}" = 1 ] && echo "port ${VPN_PORT_OF[$key]}" || echo 'on no interface'), certificate '${VPN_CERT_OF[$key]}'"
    done
    log "FortiGate: ${FGT_VERSION:-version not readable with this account}${vpn_text:-; SSL VPN: not in use}; admin HTTPS: $( [ -n "$ADMIN_NOTE" ] && echo "$ADMIN_NOTE" || echo "port $ADMIN_PORT, certificate '${ADMIN_CERT}'"); cfg-save: ${CFG_SAVE:-${CFG_NOTE:-automatic}}"
    return 0
}

# Which VDOMs this account works in; nobody names a VDOM (owner 20-11-2026). Measured on FortiOS 7.4.13 with several
# VDOMs: a global administrator is let into 'config global'; the administrator of one VDOM is refused 'config global'
# and 'config vdom', and its session stands in its VDOM; the administrator of several VDOMs is refused 'config global',
# is let into 'config vdom', and starts at the top, where every VDOM command is refused. FortiGate shows it no list of
# its VDOMs, only 'Current virtual domain', so it works in that VDOM. An admin profile with read-write on System and
# VPN and cli-get/show/config is refused 'get system status' itself; its 'config global' is answered on a FortiGate with
# several VDOMs, and without VDOMs 'get system global' answers.
detect_scope() {  # $1 = 1 when 'get system status' answered
    local names=() name
    printf 'config global\nend\n' > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    if ! fgt_refused; then
        MULTI_VDOM=1
        printf 'config global\nget system vdom-property\nend\n' > "$WORK/batch"
        fgt "$WORK/batch" || return 1
        while IFS= read -r name; do names+=("$name"); done < <(fgt_names)
        # Without the list the walk would see one VDOM and could call the job done; it is tried again instead.
        if [ ${#names[@]} = 0 ]; then
            fail VDOM_LIST "FortiGate runs with multiple VDOMs and did not list them to the global administrator '$FGT_USER' (config global, get system vdom-property), so the script cannot tell which VDOMs' SSL VPN to read. FortiGate answered: $(fgt_answer)"
            return 1
        fi
        VDOMS=("${names[@]}")
        if [ -z "$HOME_VDOM" ]; then
            printf 'config global\nget system global\nend\n' > "$WORK/batch"
            fgt "$WORK/batch" || return 1
            HOME_VDOM=$(fgt_value management-vdom)
            if [ -z "$HOME_VDOM" ] || [[ " ${VDOMS[*]} " != *" $HOME_VDOM "* ]]; then HOME_VDOM=${VDOMS[0]}; fi
        fi
        log "FortiGate runs with multiple VDOMs; '$FGT_USER' is a global administrator, so SSL VPN is read in each VDOM ($(comma_list "${VDOMS[@]}")) and admin HTTPS in global"
        return 0
    fi
    printf 'config vdom\nend\n' > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    if ! fgt_refused; then
        MULTI_VDOM=1 VDOM_ADMIN=1 VDOM_SCOPED=1
        if [ -z "$HOME_VDOM" ]; then
            fail NO_ACCESS "'get system status' is refused to '$FGT_USER', which administers several VDOMs, so the script cannot tell which VDOM it works in. Give the account's admin profile read access to System, or run setup with an account of the one VDOM the certificate belongs to"
            return 1
        fi
        VDOMS=("$HOME_VDOM")
        log "FortiGate runs with multiple VDOMs; '$FGT_USER' administers several VDOMs, and FortiGate shows it only the one it starts in, '$HOME_VDOM', so it works in that VDOM"
        return 0
    fi
    if [ "$1" = 0 ]; then
        # Status refused and neither scope: no VDOMs when the global settings answer. Otherwise the session is taken to
        # stand in one VDOM (SCOPE_GUESSED): FortiGate shows nothing that says so, so only this certificate's own object
        # or a certificate for the same name is changed there, never what SSL VPN used whatever it was.
        printf 'get system global\n' > "$WORK/batch"
        fgt "$WORK/batch" || return 1
        fgt_refused || return 0
        SCOPE_GUESSED=1
    fi
    MULTI_VDOM=1 VDOM_ADMIN=1
    VDOMS=("$HOME_VDOM")
    if [ "$SCOPE_GUESSED" = 1 ]; then
        log "FortiGate shows '$FGT_USER' neither its status nor its global settings, so it works where its session stands, and only where SSL VPN uses this certificate or a certificate for the same name"
    else
        log "FortiGate runs with multiple VDOMs; '$FGT_USER' is an administrator of VDOM '$HOME_VDOM', so it works in that VDOM"
    fi
    return 0
}

# The HA role from 'get system ha status' in $WORK/out: 'Mode: Standalone' alone, or in a cluster one line per unit
# such as 'Secondary : FGT-B, FGVM02, HA cluster index = 0' (FortiOS 7.x; 'Slave'/'Backup' in 6.x; documented, the lab
# has no cluster). The unit this session is on is the one with the prompt's host name.
ha_role() {
    local mode host role
    mode=$(fgt_value Mode)
    [ -n "$mode" ] || return 0
    if [[ ${mode,,} == *standalone* ]]; then printf 'standalone'; return 0; fi
    host=$(tr -d '\r' < "$WORK/out" | sed -n -E 's/^([^ ]+) (\([^)]*\) )?[#$].*/\1/p' | head -n 1)
    role=$(tr -d '\r' < "$WORK/out" | sed -E 's/^([^ ]+ (\([^)]*\) )?[#$] )+//' | awk -v h="$host" '
        match($0, /^[[:space:]]*(Primary|Master|Secondary|Slave|Backup)[[:space:]]*:/) {
            r = $0; sub(/^[[:space:]]*/, "", r); kind = r; sub(/[[:space:]]*:.*/, "", kind)
            unit = r; sub(/^[^:]*:[[:space:]]*/, "", unit); sub(/[[:space:]]*,.*/, "", unit)
            if (h != "" && unit == h) { print tolower(kind); exit }
        }')
    printf '%s%s' "$mode" "${role:+, $role}"
}

# SSL VPN of VDOM $1 (empty without VDOMs), from the full settings: a VDOM administrator's 'get vpn ssl settings |
# grep servercert' came back empty at a customer on 7.4.13, the full read did not.
read_ssl_vpn() {
    local vdom=$1 key cert
    key=$(vkey "$vdom")
    printf 'get vpn ssl settings\n' | in_vdom "$vdom" > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    if fgt_refused || ! grep -q 'servercert' "$WORK/out"; then return 0; fi
    cert=$(fgt_value servercert)
    VPN_CERT_OF[$key]=$cert
    VPN_PORT_OF[$key]=$(fgt_value port)
    : "${VPN_PORT_OF[$key]:=443}"
    VPN_ON_OF[$key]=0 VPN_IN_USE_OF[$key]=0
    [ "$(fgt_value status)" = disable ] && return 0
    VPN_ON_OF[$key]=1
    # SSL VPN serves nothing without an interface to listen on.
    [ -n "$(fgt_value source-interface)" ] && VPN_IN_USE_OF[$key]=1
    [ -n "$cert" ] || return 0
    printf 'get vpn certificate local details "%s"\n' "$cert" | in_vdom "$vdom" > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    VPN_CN_OF[$key]=$(tr -d '\r' < "$WORK/out" | sed -n -E 's/^.*Subject:.*CN ?= ?([^,]*).*/\1/p' | head -n 1 | sed -E 's/[[:space:]]+$//')
    VPN_FP_OF[$key]=$(tr -d '\r' < "$WORK/out" | sed -n 's/.*Fingerprint:[[:space:]]*//p' | head -n 1 | tr -d ' :' | tr 'A-F' 'a-f')
    return 0
}

# Local certificates: name -> SHA-256 and common name. The details are read for the objects this script owns and
# the one admin HTTPS uses, or for all of them with "inventory all".
declare -A INV_FP=() INV_CN=() INV_GLOBAL=()
inventory() {
    local name names=() line current=""
    INV_FP=() INV_CN=() INV_GLOBAL=()
    printf 'get vpn certificate local\n' | in_vdom > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    if fgt_refused; then
        fail NO_ACCESS "FortiGate refused to list its local certificates to '$FGT_USER': $(fgt_answer)"
        return 1
    fi
    while IFS= read -r name; do names+=("$name"); done < <(fgt_names)
    if [ "${MULTI_VDOM:-0}" = 1 ]; then
        # A VDOM also lists the global objects, marked 'set range global'; those are deleted in global.
        printf 'show vpn certificate local\n' | in_vdom > "$WORK/batch"
        fgt "$WORK/batch" || return 1
        while IFS= read -r name; do INV_GLOBAL[$name]=1; done < <(tr -d '\r' < "$WORK/out" \
            | awk '/^[[:space:]]*edit "/ { n = $0; sub(/^[[:space:]]*edit "/, "", n); sub(/"[[:space:]]*$/, "", n) } /^[[:space:]]*set range global/ { print n }')
    fi
    : > "$WORK/batch.in"
    for name in "${names[@]}"; do
        if [ "${1:-}" = all ] || own_object "$name" || legacy_object "$name" || [ "$name" = "${ADMIN_CERT:-}" ]; then
            printf 'get vpn certificate local details "%s"\n' "$name" >> "$WORK/batch.in"
        fi
        INV_FP[$name]=""
    done
    [ -s "$WORK/batch.in" ] || return 0
    in_vdom < "$WORK/batch.in" > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    while IFS= read -r line; do
        line=${line#"${line%%[![:space:]]*}"}
        case "$line" in
            Name:*) current=$(printf '%s' "${line#Name:}" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//') ;;
            Subject:*) [ -n "$current" ] && INV_CN[$current]=$(printf '%s' "$line" | sed -n -E 's/.*CN ?= ?([^,]*).*/\1/p' | sed -E 's/[[:space:]]+$//') ;;
            Fingerprint:*) [ -n "$current" ] && INV_FP[$current]=$(printf '%s' "${line#Fingerprint:}" | tr -d ' :' | tr 'A-F' 'a-f') ;;
        esac
    done < <(tr -d '\r' < "$WORK/out" | sed -E 's/^([^ ]+ (\([^)]*\) )?[#$] )+//')
    return 0
}

# ---------------------------------------------------------------------------------------------------------------
# Which settings to point at the certificate (see the top of this file). ROLES: "vpn:<VDOM>" (empty VDOM without
# VDOMs) and "admin".
# ---------------------------------------------------------------------------------------------------------------
role_wanted() {  # $1 = the name the setting uses now
    local current=$1
    [ -z "$current" ] && return 1
    [ "$current" = "$OBJECT" ] && return 0
    own_object "$current" && return 0
    same_name "${INV_CN[$current]:-}" && return 0
    return 1
}

choose_roles() {
    local name key cert why serves=0
    ROLES=()
    for name in "${VDOMS[@]}"; do
        key=$(vkey "$name")
        [ "${VPN_ON_OF[$key]:-0}" = 1 ] || continue
        cert=${VPN_CERT_OF[$key]}
        why=""
        if [ -n "$cert" ] && { [ "$cert" = "$OBJECT" ] || own_object "$cert"; }; then why="uses this certificate's object '$cert'"
        elif same_name "${VPN_CN_OF[$key]:-}"; then why="uses '$cert' for the same name ${VPN_CN_OF[$key]}"
        elif [ "${VPN_IN_USE_OF[$key]}" = 1 ] && factory_object "$cert" && [ "$MULTI_VDOM" = 0 ]; then why="uses the factory certificate '$cert'"
        # The administrator of one VDOM: its SSL VPN takes the certificate whatever it used, as setting it is what that
        # administrator has the script do (as the Windows script fgt-2.2, which the customer runs). Not the
        # administrator of several VDOMs: its login does not say which of them the certificate belongs to. Nor an account
        # whose VDOM is only guessed (SCOPE_GUESSED): FortiGate does not tell it that it has one.
        elif [ "$VDOM_ADMIN" = 1 ] && [ "$VDOM_SCOPED" = 0 ] && [ "$SCOPE_GUESSED" = 0 ]; then why="is the certificate this VDOM's administrator sets (it used '$cert')"
        fi
        if [ -n "$why" ]; then
            ROLES+=("vpn:$name")
            [ "${VPN_IN_USE_OF[$key]}" = 1 ] && serves=1
            log "$(vpn_label "$name") $why: it gets the certificate"
        elif [ "${VPN_IN_USE_OF[$key]}" = 1 ] && factory_object "$cert" && { [ "$VDOM_ADMIN" = 0 ] || [ "$VDOM_SCOPED" = 1 ] || [ "$SCOPE_GUESSED" = 1 ]; }; then
            log "$(vpn_label "$name") uses the factory certificate '$cert' and is left as it is: with several VDOMs, a factory certificate does not say that this certificate belongs to this VDOM"
        elif [ "$MULTI_VDOM" = 1 ]; then
            log "$(vpn_label "$name") uses '$cert', which is not this certificate or a certificate for $LEAF_CN, so it is left as it is"
        else
            log "$(vpn_label "$name") uses '$cert', which is not this certificate, a certificate for $LEAF_CN or a factory certificate on an interface, so it is left as it is"
        fi
    done
    if [ -n "$ADMIN_NOTE" ]; then
        # detect has logged why admin HTTPS stays as it is.
        [ ${#ROLES[@]} -gt 0 ] && return 0
        if [ "$SCOPE_GUESSED" = 1 ]; then
            fail NO_ROLE "SSL VPN uses neither this certificate nor a certificate for $LEAF_CN, and FortiGate shows '$FGT_USER' neither its status nor its global settings, so the script cannot tell that SSL VPN is this certificate's, and nothing was changed. Give the account's admin profile read access to System as the guide describes, or point SSL VPN at a certificate for $LEAF_CN once, and the next attempt takes it over: in a day, or at once when you run the deploy step of the guide again"
        elif [ "$VDOM_SCOPED" = 1 ]; then
            fail NO_ROLE "SSL VPN in VDOM '$HOME_VDOM' uses neither this certificate nor a certificate for $LEAF_CN, and admin HTTPS is global, which '$FGT_USER' cannot change, so nothing was changed. '$FGT_USER' administers several VDOMs, and FortiGate shows it only '$HOME_VDOM'. Run setup with the administrator account of the one VDOM the certificate belongs to, or point SSL VPN in '$HOME_VDOM' at a certificate for $LEAF_CN once, and the next attempt takes it over: in a day, or at once when you run the deploy step of the guide again"
        elif [ "$VDOM_ADMIN" = 1 ]; then
            fail NO_ROLE "SSL VPN is not enabled in VDOM '$HOME_VDOM', and admin HTTPS is global, which '$FGT_USER' cannot change, so nothing was changed. Enable SSL VPN in this VDOM, and the next attempt sets the certificate on it: in a day, or at once when you run the deploy step of the guide again"
        elif [ "$MULTI_VDOM" = 1 ]; then
            fail NO_ROLE "no SSL VPN in any VDOM uses this certificate or a certificate for $LEAF_CN, and FortiGate does not show '$FGT_USER' admin HTTPS, so nothing was changed. With several VDOMs the script does not take over a factory certificate on SSL VPN, because it cannot tell which VDOM this certificate belongs to. Run the guide with the administrator account of the VDOM it belongs to, or point SSL VPN in that VDOM at a certificate for $LEAF_CN once, and the next attempt takes it over: in a day, or at once when you run the deploy step of the guide again"
        else
            fail NO_ROLE "no SSL VPN uses a FairSSL certificate, a certificate for $LEAF_CN or a factory certificate on an interface, and FortiGate does not show '$FGT_USER' admin HTTPS, so nothing was changed. Point SSL VPN at a factory certificate while it listens on an interface, and the next attempt takes it over: in a day, or at once when you run the deploy step of the guide again"
        fi
        return 1
    fi
    # Admin HTTPS takes over a factory certificate unless an SSL VPN listening on an interface gets this certificate:
    # SSL VPN may use a certificate of the customer's own, or only an earlier FairSSL object without serving it.
    if role_wanted "$ADMIN_CERT" || { [ "$serves" = 0 ] && factory_object "$ADMIN_CERT"; }; then
        ROLES+=(admin)
        log "admin HTTPS (certificate '$ADMIN_CERT') gets the certificate"
    fi
    if [ ${#ROLES[@]} = 0 ] && [ "$MULTI_VDOM" = 1 ]; then
        fail NO_ROLE "no SSL VPN in any VDOM uses this certificate or a certificate for $LEAF_CN, and admin HTTPS (certificate '$ADMIN_CERT') uses no factory certificate this script may take over, so nothing was changed. With several VDOMs the script does not take over a factory certificate on SSL VPN, because it cannot tell which VDOM this certificate belongs to. Run the guide with the administrator account of the VDOM it belongs to, or point SSL VPN in that VDOM at a certificate for $LEAF_CN once, and the next attempt takes it over: in a day, or at once when you run the deploy step of the guide again"
        return 1
    fi
    if [ ${#ROLES[@]} = 0 ]; then
        fail NO_ROLE "neither SSL VPN nor admin HTTPS (certificate '$ADMIN_CERT') uses a FairSSL certificate, a certificate for $LEAF_CN or a factory certificate this script may take over (on admin HTTPS, or on SSL VPN while it listens on an interface), so nothing was changed. Point admin HTTPS, or SSL VPN when it listens on an interface, at a factory certificate once, and the next attempt takes it over: in a day, or at once when you run the deploy step of the guide again"
        return 1
    fi
    return 0
}

role_label() { if [ "$1" = admin ]; then printf 'admin HTTPS'; else vpn_label "${1#vpn:}"; fi; }
role_cert() { if [ "$1" = admin ]; then printf '%s' "$ADMIN_CERT"; else printf '%s' "${VPN_CERT_OF[$(vkey "${1#vpn:}")]}"; fi; }
role_port() { if [ "$1" = admin ]; then printf '%s' "$ADMIN_PORT"; else printf '%s' "${VPN_PORT_OF[$(vkey "${1#vpn:}")]}"; fi; }
role_fp() { if [ "$1" = admin ]; then printf '%s' "${INV_FP[$ADMIN_CERT]:-}"; else printf '%s' "${VPN_FP_OF[$(vkey "${1#vpn:}")]:-}"; fi; }
unchanged_fps_on() {  # $1 port: the certificates of the settings on that port that this attempt leaves as they are
    local name key
    if [[ " ${ROLES[*]} " != *" admin "* ]] && [ "${ADMIN_PORT:-}" = "$1" ]; then printf '%s\n' "${INV_FP[$ADMIN_CERT]:-}"; fi
    for name in "${VDOMS[@]}"; do
        [[ " ${ROLES[*]} " == *" vpn:$name "* ]] && continue
        key=$(vkey "$name")
        [ "${VPN_PORT_OF[$key]:-}" = "$1" ] && printf '%s\n' "${VPN_FP_OF[$key]:-}"
    done
    return 0
}
role_set() {  # $1 role, $2 certificate name: the batch that points the setting at it
    if [ "$1" = admin ]; then printf 'config system global\nset admin-server-cert "%s"\nend\n' "$2" | in_global
    else printf 'config vpn ssl settings\nset servercert "%s"\nend\n' "$2" | in_vdom "${1#vpn:}"; fi
}
role_read() {  # $1 role: sets ROLE_VALUE from FortiGate's full settings
    if [ "$1" = admin ]; then printf 'get system global\n' | in_global > "$WORK/batch"
    else printf 'get vpn ssl settings\n' | in_vdom "${1#vpn:}" > "$WORK/batch"; fi
    fgt "$WORK/batch" || return 1
    if [ "$1" = admin ]; then ROLE_VALUE=$(fgt_value admin-server-cert); else ROLE_VALUE=$(fgt_value servercert); fi
}
role_remember() {  # $1 role, $2 the certificate it uses now
    if [ "$1" = admin ]; then ADMIN_CERT=$2; else VPN_CERT_OF[$(vkey "${1#vpn:}")]=$2; fi
}

# ---------------------------------------------------------------------------------------------------------------
# TLS: what FortiGate serves on host:port. Sets SERVED_FP and SERVED_CHAIN (SHA-256 of the certificates after the
# leaf). Returns 1 when no handshake was possible.
# ---------------------------------------------------------------------------------------------------------------
served() {
    local host=$1 port=$2 sni=${LEAF_CN/#\*./fairssl-check.} target f
    SERVED_FP="" SERVED_CHAIN=""
    if [[ $host == *:* ]]; then target="[$host]:$port"; else target="$host:$port"; fi
    timeout "$SILENCE_LIMIT" openssl s_client -connect "$target" -servername "$sni" -showcerts < /dev/null 2> /dev/null \
        | split_pem tls
    [ -s "$WORK/tls-01.crt" ] || return 1
    SERVED_FP=$(cert_sha256 "$WORK/tls-01.crt")
    for f in "$WORK"/tls-*.crt; do
        [ "$f" = "$WORK/tls-01.crt" ] || SERVED_CHAIN="$SERVED_CHAIN $(cert_sha256 "$f")"
    done
    return 0
}

chain_served() {
    local f
    for f in "${CHAIN_FILES[@]}"; do
        [[ " $SERVED_CHAIN " == *" $(cert_sha256 "$f") "* ]] || return 1
    done
    return 0
}

# Waits until host:port serves the new certificate. 0 = served with its chain, 2 = leaf without its chain,
# 3 = another certificate, 4 = no handshake. $3 = 0 when a handshake worked before the switch; a listener that
# could not be reached before is not waited for.
await_served() {
    local host=$1 port=$2 before=${3:-4} waited=0 result=4
    while :; do
        if served "$host" "$port"; then
            if [ "$SERVED_FP" = "$LEAF_FP" ]; then
                chain_served && return 0
                result=2
            else
                result=3
            fi
        else
            result=4
            [ "$before" != 0 ] && return 4
        fi
        [ "$waited" -ge "$SWITCH_WAIT" ] && return "$result"
        sleep "$SWITCH_POLL"
        waited=$((waited + SWITCH_POLL))
    done
}

# ---------------------------------------------------------------------------------------------------------------
# One attempt: upload, bind, verify, clean up.
# ---------------------------------------------------------------------------------------------------------------
verified_by() { VERIFIED_HOW="${VERIFIED_HOW:+$VERIFIED_HOW, }$1"; }

attempt() {
    local code text
    FAIL_CODE="" FAIL_TEXT="" VERIFIED_HOW="" WROTE=0 DETECTED=0 ROLES=() CA_RESULTS=()
    # What an earlier attempt wrote and FortiGate did not save is saved by this one before it can end as installed.
    [ -e "$STATE_DIR/$NAME.unsaved" ] && WROTE=1
    attempt_steps && return 0
    # A failed attempt may have uploaded the certificate or changed a setting; with cfg-save manual FortiGate loses that
    # at the next restart, so it is saved. An attempt that changed nothing saves nothing: with cfg-save manual a save
    # would also keep other administrators' pending changes. A refused save replaces only NOT_SHOWN, whose change
    # FortiGate accepted; any other failure keeps its code and says that FortiGate did not save either (after a
    # rollback, a restart of FortiGate would otherwise bring back the certificate the listener stopped answering with).
    if [ "$WROTE" = 1 ] && [ "$DETECTED" = 1 ] && [ "$FAIL_CODE" != CFG_SAVE_FAILED ]; then
        code=$FAIL_CODE text=$FAIL_TEXT
        if save_config; then FAIL_CODE=$code FAIL_TEXT=$text
        elif [ "$code" != NOT_SHOWN ]; then FAIL_TEXT="$text. FortiGate did not save its configuration either, so the next attempt saves it ($FAIL_TEXT)" FAIL_CODE=$code; fi
    fi
    return 1
}

attempt_steps() {
    local name role port result labels
    read_certificate || return 1
    log "Certificate: $LEAF_CN, SHA-256 ${LEAF_FP:0:16}..., expires $LEAF_EXPIRY, ${#CHAIN_FILES[@]} intermediate(s); FortiGate object $OBJECT"
    detect || return 1
    DETECTED=1
    if [ "$CFG_SAVE" = revert ]; then
        # Saving would also keep another administrator's changes that revert is there to undo.
        fail CFG_SAVE_REVERT "FortiGate's cfg-save is 'revert': FortiGate undoes every change that is not saved, and saving would also keep other administrators' changes that are waiting to be undone, so nothing was changed. Set cfg-save to 'automatic' or 'manual' (config system global), and the next attempt installs the certificate: in a day, or at once when you run the deploy step of the guide again"
        return 1
    fi
    choose_roles || return 1

    # The intermediates go to FortiGate's CA store before the certificate, as Deploy-FortiGate.ps1 sends them: FortiGate
    # serves the intermediates it got with the certificate only until it restarts, and after a restart only those its
    # CA store holds (FortiOS 7.4.13, measured 23-11-2026).
    ca_store_upload "${ROLES[@]}" || return 1

    # Upload, unless FortiGate already holds this certificate (under our name or any other).
    local existing=""
    for name in "${!INV_FP[@]}"; do holds_leaf "${INV_FP[$name]}" && existing=$name; done
    if holds_leaf "${INV_FP[$OBJECT]:-}"; then existing=$OBJECT; fi
    if [ -n "$existing" ]; then
        OBJECT=$existing
        log "FortiGate already holds this certificate as '$OBJECT'"
    else
        upload "${CHAIN_FILES[@]}" || return 1
    fi

    # One TLS handshake per port before the switch; the settings behind each port. An address that answers with
    # another certificate than the setting uses belongs to another listener on that port (admin HTTPS beside SSL VPN
    # on 443 answered so on 7.4.13, measured), and says nothing about the setting.
    declare -A PORT_ROLES=() BEFORE_OK=() OTHER=()
    declare -g -A PREVIOUS=()
    for role in "${ROLES[@]}"; do
        PREVIOUS[$role]=$(role_cert "$role")
        port=$(role_port "$role")
        PORT_ROLES[$port]="${PORT_ROLES[$port]:-} $role"
    done
    local expected mine known changes
    for port in "${!PORT_ROLES[@]}"; do
        BEFORE_OK[$port]=4
        # shellcheck disable=SC2086 # role names hold no spaces; the list is split on purpose
        set -- ${PORT_ROLES[$port]}
        changes=0
        for role in "$@"; do [ "$(role_cert "$role")" = "$OBJECT" ] || changes=1; done
        [ "$changes" = 1 ] || continue
        served "$FGT_HOST" "$port" || continue
        # The answer is this listener when it is the certificate of any setting behind the port (two VDOMs' SSL VPN
        # can share one), and another listener's only when every one of them is known and none matches.
        mine=0 known=1
        for role in "$@"; do
            expected=$(role_fp "$role")
            [ "$SERVED_FP" = "$expected" ] && mine=1
            [ ${#expected} = 64 ] || known=0
        done
        if [ "$mine" = 1 ]; then BEFORE_OK[$port]=0
        elif [ "$known" = 1 ] || grep -q -x -F "$SERVED_FP" <<< "$(unchanged_fps_on "$port")"; then OTHER[$port]=1
        else BEFORE_OK[$port]=0; fi
    done

    bind || return 1
    if [ "$WROTE" = 1 ]; then save_config || return 1; fi

    # The TLS handshake is information: this server often reaches FortiGate only over SSH, and the configuration read
    # over SSH decides (owner 20-11-2026). Only a listener that answered before the switch and gives no handshake
    # after it gets the previous certificate back, on the settings behind that port.
    for port in "${!PORT_ROLES[@]}"; do
        labels=""
        for role in ${PORT_ROLES[$port]}; do labels="${labels:+$labels and }$(role_label "$role")"; done
        if [ -n "${OTHER[$port]:-}" ]; then
            log "$labels: $FGT_HOST answers on port $port with another listener's certificate, so the configuration read over SSH decides"
            verified_by "$labels (configuration)"
            continue
        fi
        await_served "$FGT_HOST" "$port" "${BEFORE_OK[$port]}"; result=$?
        case "$result" in
            0) log "$labels on port $port serves the new certificate with its intermediate(s)"; verified_by "$labels (TLS)" ;;
            2) log "$labels on port $port serves the new certificate, but this server sees it without its intermediate(s): FortiGate sends neither the ones uploaded with the certificate nor its CA store's"; verified_by "$labels (TLS, no chain)" ;;
            3) log "$labels on port $port: this server still sees another certificate there (SHA-256 ${SERVED_FP:0:16}...) ${SWITCH_WAIT} seconds after the switch; the configuration read over SSH shows '$OBJECT'"
               verified_by "$labels (configuration)" ;;
            4)
                if [ "${BEFORE_OK[$port]}" = 0 ]; then
                    if rollback_port "$port"; then
                        fail ROLLED_BACK "$labels on $FGT_HOST:$port stopped answering TLS after the switch to '$OBJECT', so the previous certificate was put back"
                    else
                        fail ROLLBACK_FAILED "$labels on $FGT_HOST:$port stopped answering TLS after the switch to '$OBJECT', and the previous certificate could not be put back: $ROLLBACK_TEXT. Check the listener on FortiGate and set its certificate by hand"
                    fi
                    return 1
                fi
                log "$labels on port $port: no TLS handshake from this server, so the configuration read over SSH decides"
                verified_by "$labels (configuration)" ;;
        esac
    done

    # A FortiGate that saves its configuration by hand also keeps the intermediates and the deletions.
    cleanup_objects
    if [ "$WROTE" = 1 ]; then save_config || return 1; fi
    return 0
}

upload() {
    local chain_files=("$@") name
    # A global administrator with multiple VDOMs uploads in global: admin HTTPS refuses a VDOM's certificate (-651,
    # measured on 7.4.13), and SSL VPN in the VDOM uses the global object as well.
    local section='vpn certificate local' scope=in_vdom where=""
    if global_admin_on_vdoms; then section='certificate local' scope=in_global where=" in global"; fi
    {
        printf 'config %s\n' "$section"
        printf 'edit "%s"\n' "$OBJECT"
        printf 'set private-key "%s"\n' "$(tr -d '\r' < "$KEY_FILE")"
        printf 'set certificate "%s"\n' "$(cat "$LEAF_FILE" "${chain_files[@]}" | tr -d '\r')"
        printf 'set comments "FairSSL %s, expires %s"\n' "$LEAF_CN" "${LEAF_EXPIRY%%T*}"
        printf 'next\nend\n'
    } | "$scope" > "$WORK/batch"
    log "Uploading the certificate$( [ ${#chain_files[@]} -gt 0 ] && echo " with ${#chain_files[@]} intermediate(s)") as '$OBJECT'$where"
    wrote
    fgt "$WORK/batch" || { rm -f "$WORK/batch"; return 1; }
    rm -f "$WORK/batch"
    local answer
    answer=$(fgt_answer)
    inventory || return 1
    if holds_leaf "${INV_FP[$OBJECT]:-}"; then
        [ -n "$answer" ] && log "FortiGate noted: $answer"
        return 0
    fi
    # The same certificate under another name ("This local certificate is duplicated"): use that object.
    [[ $answer == *duplicated* ]] && { inventory all || return 1; }
    for name in "${!INV_FP[@]}"; do
        if holds_leaf "${INV_FP[$name]}"; then
            log "FortiGate holds this certificate as '$name' already; using it"
            OBJECT=$name
            return 0
        fi
    done
    if [ ${#chain_files[@]} -gt 0 ]; then
        log "FortiGate did not store the certificate with its intermediates ($answer); trying the certificate alone"
        upload
        return
    fi
    # The fingerprint FortiGate shows for the object is the proof that it holds this certificate (SHA-256, or SHA-1 on
    # an older FortiOS); without it nothing is pointed at the object.
    fail UPLOAD_FAILED "FortiGate did not keep the certificate as '$OBJECT', or shows no fingerprint for it that matches. FortiGate answered: ${answer:-nothing}"
}

# Points each chosen setting at the object, one batch per setting so a refusal names its setting, then reads the full
# settings back every READBACK_POLL seconds for up to READBACK_WAIT (owner 20-11-2026). A refusal is a failure; a
# change FortiGate accepted and does not show yet ends the attempt as NOT_SHOWN, which is not an error.
bind() {
    local role changed=() unseen=() started labels="" unseen_labels=""
    for role in "${ROLES[@]}"; do
        [ "$(role_cert "$role")" = "$OBJECT" ] && continue
        role_set "$role" "$OBJECT" > "$WORK/batch"
        log "Pointing $(role_label "$role") (was '$(role_cert "$role")') at '$OBJECT'"
        wrote
        fgt "$WORK/batch" || return 1
        if fgt_refused; then
            fail BIND_FAILED "FortiGate refused to set $(role_label "$role") to '$OBJECT': $(fgt_answer)"
            return 1
        fi
        changed+=("$role")
        labels="${labels:+$labels and }$(role_label "$role")"
    done
    if [ ${#changed[@]} = 0 ]; then
        log "The chosen settings already use '$OBJECT'"
        return 0
    fi
    started=$SECONDS
    while :; do
        unseen=()
        for role in "${changed[@]}"; do
            role_read "$role" || return 1
            [ "$ROLE_VALUE" = "$OBJECT" ] || unseen+=("$role")
        done
        [ ${#unseen[@]} = 0 ] && break
        [ $((SECONDS - started)) -ge "$READBACK_WAIT" ] && break
        sleep "$READBACK_POLL"
    done
    for role in "${changed[@]}"; do role_remember "$role" "$OBJECT"; done
    if [ ${#unseen[@]} -gt 0 ]; then
        # attempt saves the change.
        for role in "${unseen[@]}"; do unseen_labels="${unseen_labels:+$unseen_labels and }$(role_label "$role")"; done
        FAIL_CODE=NOT_SHOWN
        FAIL_TEXT="The certificate is installed on FortiGate as '$OBJECT' and set on $labels. FortiGate does not show the change on $unseen_labels yet, $READBACK_WAIT seconds after it accepted it."
        return 1
    fi
    log "FortiGate shows $labels on '$OBJECT'"
    return 0
}

# The settings behind port $1 that this attempt moved go back to the certificate they used before. Returns 1, with
# ROLLBACK_TEXT, when one of them is still on the new object: FortiGate refused, there is no connection (a FortiGate
# that stopped answering altogether), or the setting had no certificate before.
rollback_port() {
    local role failed=""
    ROLLBACK_TEXT=""
    for role in ${PORT_ROLES[$1]}; do
        [ "${PREVIOUS[$role]-$OBJECT}" = "$OBJECT" ] && continue
        if [ -z "${PREVIOUS[$role]}" ]; then
            failed="${failed:+$failed; }$(role_label "$role") is still on '$OBJECT' (it had no certificate before)"
            continue
        fi
        role_set "$role" "${PREVIOUS[$role]}" > "$WORK/batch"
        wrote
        if ! fgt "$WORK/batch"; then
            failed="${failed:+$failed; }$(role_label "$role") is still on '$OBJECT' ($FAIL_TEXT)"
        elif fgt_refused; then
            failed="${failed:+$failed; }$(role_label "$role") is still on '$OBJECT' (FortiGate refused '${PREVIOUS[$role]}': $(fgt_answer))"
        else
            log "$(role_label "$role") points at its previous certificate '${PREVIOUS[$role]}' again"
            role_remember "$role" "${PREVIOUS[$role]}"
        fi
    done
    ROLLBACK_TEXT=$failed
    [ -z "$failed" ]
}

# The CA store is offered every intermediate it does not hold, on every attempt and before the certificate is
# uploaded: after a restart FortiGate serves only the intermediates its CA store holds. They go to the store of each
# VDOM whose SSL VPN is among the settings $@; admin HTTPS of a FortiGate with VDOMs is global and uses no VDOM's
# store. FortiGate's list is read again afterwards, so the log and the report say what the store holds. Whatever
# FortiGate answers is never an error in itself (the lab's FortiGate-VM refuses every CA with an RSA key: "Input is
# not a valid CA certificate"), and no CA object is ever deleted. Returns 1 only when FortiGate cannot be reached,
# which ends the attempt as at any other step.
ca_store_fps() {
    printf 'get vpn certificate ca details\n' | in_vdom "$1" > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    CA_FPS=$(tr -d '\r' < "$WORK/out" | sed -n 's/.*Fingerprint:[[:space:]]*//p' | tr -d ' :' | tr 'A-F' 'a-f')
}

ca_store_upload() {
    local role vdom vdoms=() f fp where offered
    local -A answer
    [ ${#CHAIN_FILES[@]} -gt 0 ] || return 0
    if [ "${MULTI_VDOM:-0}" = 1 ]; then
        for role in "$@"; do
            [ "$role" = admin ] && continue
            [[ " ${vdoms[*]} " == *" ${role#vpn:} "* ]] || vdoms+=("${role#vpn:}")
        done
    else
        vdoms=("")
    fi
    for vdom in "${vdoms[@]}"; do
        where=""
        [ -n "$vdom" ] && where=" of VDOM '$vdom'"
        ca_store_fps "$vdom" || return 1
        offered=() answer=()
        for f in "${CHAIN_FILES[@]}"; do
            fp=$(cert_sha256 "$f")
            if grep -q -x "$fp" <<< "$CA_FPS"; then
                log "FortiGate's CA store$where already holds intermediate ${fp:0:12}"
                CA_RESULTS+=("${fp:0:12}: already in the CA store$where")
                continue
            fi
            { printf 'config vpn certificate ca\nedit "fssl-ca-%s"\nset ca "' "${fp:0:12}"; tr -d '\r' < "$f"; printf '"\nnext\nend\n'; } | in_vdom "$vdom" > "$WORK/batch"
            wrote
            fgt "$WORK/batch" || return 1
            answer[$fp]=$(fgt_answer)
            offered+=("$fp")
        done
        [ ${#offered[@]} -gt 0 ] || continue
        ca_store_fps "$vdom" || return 1
        for fp in "${offered[@]}"; do
            if grep -q -x "$fp" <<< "$CA_FPS"; then
                log "FortiGate's CA store$where took intermediate ${fp:0:12} as fssl-ca-${fp:0:12}"
                CA_RESULTS+=("${fp:0:12}: added to the CA store$where as fssl-ca-${fp:0:12}")
            else
                log "FortiGate's CA store$where did not take intermediate ${fp:0:12} (FortiGate answered: ${answer[$fp]:-nothing})"
                CA_RESULTS+=("${fp:0:12}: not in the CA store$where (FortiGate answered: ${answer[$fp]:-nothing})")
            fi
        done
    done
}

# cfg-save is global. A VDOM administrator can neither read it nor run 'execute cfg save' (Unknown action 0, also with
# cfg-save manual; FortiOS 7.4.13, measured), so FortiGate's own setting applies there and the log and the report say
# so. With manual only the save keeps a change, so its answer decides; only an account with the super_admin profile may
# run it (an admin profile with read-write on System is answered Unknown action 0, measured). With revert the attempt
# changes nothing.
# WROTE: written since the last save, also by an earlier attempt ($STATE_DIR/$NAME.unsaved). Set before every command
# that changes FortiGate. An attempt that changed nothing saves nothing: with cfg-save manual a save would also keep
# other administrators' pending changes. An intermediate offered to the CA store counts as written, also when
# FortiGate refuses it, as in Deploy-FortiGate.ps1.
wrote() { WROTE=1; : > "$STATE_DIR/$NAME.unsaved"; }
saved() { WROTE=0; rm -f "$STATE_DIR/$NAME.unsaved"; }

save_config() {
    # Nothing a save would keep with automatic (FortiGate saves) or revert (nothing was changed), nor for an account
    # that cannot read cfg-save (a VDOM administrator).
    case "${CFG_SAVE:-automatic}" in
        automatic|revert) saved; return 0 ;;
    esac
    printf 'execute cfg save\n' | in_global > "$WORK/batch"
    fgt "$WORK/batch" || return 1
    if grep -q -i -E 'config saved|no config to be saved' "$WORK/out"; then
        log "Saved FortiGate's configuration (cfg-save is $CFG_SAVE)"
        saved
        return 0
    fi
    fail CFG_SAVE_FAILED "FortiGate saves its configuration by hand (cfg-save $CFG_SAVE), and 'execute cfg save' did not save it, so the change is lost at the next restart. FortiGate lets only an account with the super_admin profile run it. FortiGate answered: $(fgt_answer)"
}

# Keeps the new object, the ones the settings used before and every one a setting uses; deletes the other objects
# this script owns.
cleanup_objects() {
    local name role answer keep=() deleted=()
    keep+=("$OBJECT" "$ADMIN_CERT" "${VPN_CERT_OF[@]}")
    for role in "${!PREVIOUS[@]}"; do keep+=("${PREVIOUS[$role]}"); done
    : > "$WORK/batch"
    for name in "${!INV_FP[@]}"; do
        own_object "$name" || { legacy_object "$name" && same_name "${INV_CN[$name]:-}"; } || continue
        [[ " ${keep[*]} " == *" $name "* ]] && continue
        if [ "${MULTI_VDOM:-0}" = 1 ] && [ -n "${INV_GLOBAL[$name]:-}" ]; then
            # A global object: deleted in global, which a VDOM administrator cannot do.
            [ "${VDOM_ADMIN:-0}" = 1 ] && continue
            printf 'config certificate local\ndelete "%s"\nend\n' "$name" | in_global >> "$WORK/batch"
        else
            printf 'config vpn certificate local\ndelete "%s"\nend\n' "$name" | in_vdom >> "$WORK/batch"
        fi
        deleted+=("$name")
    done
    [ ${#deleted[@]} -eq 0 ] && return 0
    wrote
    fgt "$WORK/batch" || return 0
    answer=$(fgt_answer)
    inventory || return 0
    for name in "${deleted[@]}"; do
        if [ -n "${INV_FP[$name]+set}" ]; then
            log "Kept '$name': FortiGate would not delete it (${answer:-no answer}); another setting may use it"
        else
            log "Deleted the older certificate object '$name'"
        fi
    done
}

# ---------------------------------------------------------------------------------------------------------------
# Reports to the report address.
# ---------------------------------------------------------------------------------------------------------------
json_string() {
    local s
    s=$(printf '%s' "$1" | tr -d '\000-\010\013\014\016-\037')
    s=${s//\\/\\\\}; s=${s//\"/\\\"}; s=${s//$'\n'/\\n}; s=${s//$'\r'/\\r}; s=${s//$'\t'/\\t}
    printf '"%s"' "$s"
}

json_list() {  # the arguments as a JSON list of strings
    local item list=""
    for item in "$@"; do list="$list${list:+,}$(json_string "$item")"; done
    printf '[%s]' "$list"
}

# For example "Debian GNU/Linux 12 (bookworm)", read from /etc/os-release without running it as shell code.
os_version() {
    local name
    name=$(sed -n 's/^PRETTY_NAME=//p' "${FAIRSSL_FORTIGATE_OS_RELEASE:-/etc/os-release}" 2> /dev/null | head -n 1 | tr -d '"')
    printf '%s' "${name:-$(uname -sr)}"
}

account_kid() {
    local file
    for file in "$LEGO_PATH"/accounts/*/*/account.json; do
        [ -r "$file" ] || continue
        sed -n 's/.*"accountURL"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$file" | head -n 1 | sed 's#\\/#/#g'
        return
    done
}

queue_report() {  # $1 install_status (empty: still trying), $2 error code, $3 error text
    local kid file excerpt lego_version role vdoms=() keys=()
    # No report address: nothing is written and nothing is sent.
    [ -n "$REPORT_URL" ] || return 0
    kid=$(account_kid)
    if [ -z "$kid" ]; then log "No lego account found under $LEGO_PATH/accounts, so no report is sent"; return 0; fi
    excerpt=$(tail -c 20000 "$WORK/attempt.log" 2>/dev/null)
    lego_version=$(lego --version 2>/dev/null | sed -n 's/^lego version \([^ ]*\).*/\1/p')
    for role in "${ROLES[@]}"; do
        if [ "$role" = admin ]; then keys+=(admin); else keys+=(sslvpn); [ -n "${role#vpn:}" ] && vdoms+=("${role#vpn:}"); fi
    done
    file="$OUTBOX/$(date -u +%Y%m%dT%H%M%S)-$$-$RANDOM.json"
    {
        printf '{'
        printf '"kid":%s,' "$(json_string "$kid")"
        printf '"renewal_id":%s,' "$(json_string "$RENEWAL_ID")"
        printf '"domain":%s,' "$(json_string "${LEAF_CN:-$NAME}")"
        printf '"status":"success",'
        [ -n "${LEAF_SHA1:-}" ] && printf '"thumbprint":%s,' "$(json_string "$LEAF_SHA1")"
        [ -n "${LEAF_EXPIRY:-}" ] && printf '"expiry_at":%s,' "$(json_string "$LEAF_EXPIRY")"
        if [ -n "$1" ]; then printf '"install_status":%s,' "$(json_string "$1")"; else printf '"install_status":null,'; fi
        if [ "$1" = failure ]; then
            # The code and the sentence as Deploy-FortiGate.ps1 sends them, so the control panel shows one name for one
            # failure whichever server runs the installation.
            printf '"install_error_code":%s,' "$(json_string "$2")"
            printf '"install_error_string":%s,' "$(json_string "${3:0:500}")"
        fi
        printf '"machine_name":%s,' "$(json_string "$(hostname 2>/dev/null || uname -n)")"
        printf '"client_version":%s,' "$(json_string "lego ${lego_version:-unknown}")"
        printf '"script_version":%s,' "$(json_string "fortigate-$SCRIPT_VERSION")"
        # What runs here, for the control panel: this script and its version, the operating system, the certificate's
        # key and what FortiGate says it is. Names, versions and public fingerprints only.
        printf '"installations":[{"plugin":"script","script":"fairssl-fortigate","script_version":%s}],' "$(json_string "$SCRIPT_VERSION")"
        printf '"os_version":%s,' "$(json_string "$(os_version)")"
        [ -n "${LEAF_KEY_TYPE:-}" ] && printf '"key_type":%s,' "$(json_string "$LEAF_KEY_TYPE")"
        [ -n "${LEAF_FP:-}" ] && printf '"certificate_sha256":%s,' "$(json_string "$LEAF_FP")"
        [ -n "${DEVICE_MODEL:-}" ] && printf '"device_model":%s,' "$(json_string "$DEVICE_MODEL")"
        [ -n "${DEVICE_VERSION:-}" ] && printf '"device_version":%s,' "$(json_string "$DEVICE_VERSION")"
        printf '"meta":{"guide":"fortigate-legacy-linux","certificate_name":%s,"firewall_host":%s,"fortigate_object":%s,"fortios":%s,"verified":%s,' \
            "$(json_string "$NAME")" "$(json_string "$FGT_HOST")" "$(json_string "${OBJECT:-}")" "$(json_string "${FGT_VERSION:-}")" "$(json_string "${VERIFIED_HOW:-}")"
        printf '"ssh_client":%s,' "$(json_string "$(ssh -V 2>&1 | head -n 1)")"
        [ -n "${HA_MODE:-}" ] && printf '"ha_mode":%s,' "$(json_string "$HA_MODE")"
        if [ ${#keys[@]} -gt 0 ]; then
            printf '"roles":%s,' "$(json_list "${keys[@]}")"
            [ ${#vdoms[@]} -gt 0 ] && printf '"vdoms":%s,' "$(json_list "${vdoms[@]}")"
        fi
        [ ${#CA_RESULTS[@]} -gt 0 ] && printf '"intermediates":%s,' "$(json_list "${CA_RESULTS[@]}")"
        if [ -n "${HOME_VDOM:-}" ]; then
            printf '"vdom":%s,"vdom_admin":%s,' "$(json_string "$HOME_VDOM")" "$( [ "${VDOM_ADMIN:-0}" = 1 ] && echo true || echo false)"
        fi
        if [ -n "$2" ]; then
            printf '"attempt":%s,' "${ATTEMPT_NUMBER:-1}"
            [ -z "$1" ] && printf '"pending_code":%s,"pending_text":%s,' "$(json_string "$2")" "$(json_string "${3:0:500}")"
            [ -n "${FIRST_FAILED_AT:-}" ] && printf '"first_failed_at":%s,' "$(json_string "$FIRST_FAILED_AT")"
        fi
        [ -n "${ADMIN_NOTE:-}" ] && printf '"admin_https":%s,' "$(json_string "$ADMIN_NOTE")"
        [ -n "${CFG_NOTE:-}" ] && printf '"cfg_save":%s,' "$(json_string "$CFG_NOTE")"
        printf '"log":%s}' "$(json_string "$excerpt")"
        printf '}\n'
    } > "$file.tmp" && mv -f "$file.tmp" "$file"
}

# Sends what waits in the outbox, oldest first. Returns 1 while something is left.
flush_outbox() {
    local file answer
    [ -n "$REPORT_URL" ] || return 0
    for file in "$OLD_OUTBOX"/*.json "$OUTBOX"/*.json; do
        [ -e "$file" ] || continue
        # The proxy goes in curl's environment, so that a proxy login never stands in a command line.
        answer=$(https_proxy=$REPORT_PROXY http_proxy=$REPORT_PROXY curl -sS --connect-timeout "$SILENCE_LIMIT" --speed-limit 1 --speed-time "$SILENCE_LIMIT" \
            -H 'Content-Type: application/json' -H 'Accept: application/json' \
            -A "fairssl-fortigate/$SCRIPT_VERSION" --data-binary "@$file" "$REPORT_URL" 2>&1)
        # For the log: whole, before it is shortened, without the password and without the proxy's address and login.
        answer=$(redact "$answer")
        [ -n "$REPORT_PROXY" ] && answer=${answer//"$REPORT_PROXY"/[proxy]}
        if [[ $answer =~ \"ok\"[[:space:]]*:[[:space:]]*true ]]; then
            rm -f "$file"
            log "The receiver confirmed the report $(basename "$file" .json)"
        elif [[ $answer =~ \"errors\" ]]; then
            # The receiver read the report and refused its content, which sending it again does not change; it would
            # otherwise block every report behind it for good.
            mkdir -p "$OUTBOX/refused" && mv -f "$file" "$OUTBOX/refused/"
            log "The receiver refused the report $(basename "$file" .json) (${answer:0:300}); it is kept in $OUTBOX/refused"
        else
            log "The receiver did not confirm the report $(basename "$file" .json) (${answer:0:200}); it is sent again later"
            return 1
        fi
    done
    return 0
}

# ---------------------------------------------------------------------------------------------------------------
# Commands.
# ---------------------------------------------------------------------------------------------------------------
reported_before() { grep -q -x "$LEAF_FP" "$STATE_DIR/$NAME.reported" 2>/dev/null; }

record_result() {  # $1 = text
    printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" > "$STATE_DIR/$NAME.result.tmp" && mv -f "$STATE_DIR/$NAME.result.tmp" "$STATE_DIR/$NAME.result"
}

# One attempt plus its report. Returns 0 when FortiGate has the certificate.
attempt_and_report() {
    rm -f "$STATE_DIR/$NAME.again"
    rotate_log
    new_work_dir
    : > "$WORK/attempt.log"
    if attempt; then
        log "Installed: $LEAF_CN on FortiGate $FGT_HOST as '$OBJECT' (${VERIFIED_HOW:-no setting changed})"
        record_result "installed $OBJECT ($LEAF_CN, ${LEAF_FP:0:12}): ${VERIFIED_HOW:-}"
        # FairSSL hears of each certificate's installation once, and again when it works after attempts that failed:
        # those were reported, so the control panel must see that they ended.
        if ! reported_before || [ -e "$STATE_DIR/$NAME.failing" ]; then
            queue_report success "" ""
            reported_before || printf '%s\n' "$LEAF_FP" >> "$STATE_DIR/$NAME.reported"
        fi
        rm -f "$STATE_DIR/$NAME.failure" "$STATE_DIR/$NAME.failing"
        return 0
    fi
    record_result "failed $FAIL_CODE: $FAIL_TEXT"
    # The owner's rule (20-11-2026): FairSSL hears of a failure at the first attempt that still fails FAILURE_AFTER
    # seconds after the first failed attempt for this certificate; before that each attempt is reported as still
    # trying, which makes no event and no mail. After that, a failure that repeats unchanged is reported once a day.
    # A change FortiGate accepted and does not show yet (NOT_SHOWN) counts like any other: a FortiGate that never shows
    # it reaches FairSSL after the same 15 minutes. A step only the customer can take (customer_step) is reported at
    # once, as the next attempt comes a day later.
    local since marker=""
    FIRST_FAILED_AT=""
    since=$(failing_since)
    FIRST_FAILED_AT=$(date -u -d "@$since" +%Y-%m-%dT%H:%M:%SZ)
    if ! customer_step && [ $(( $(date +%s) - since )) -lt "$FAILURE_AFTER" ]; then
        queue_report "" "$FAIL_CODE" "$FAIL_TEXT"
        return 1
    fi
    read -r _ _ marker < "$STATE_DIR/$NAME.failing"
    if [ "$marker" != reported ] || failure_report_due; then
        queue_report failure "$FAIL_CODE" "$FAIL_TEXT"
        printf '%s %s\n' "$(date +%s)" "$FAIL_CODE" > "$STATE_DIR/$NAME.failure"
        printf '%s %s reported\n' "$since" "${LEAF_FP:-none}" > "$STATE_DIR/$NAME.failing"
    fi
    return 1
}

# NO_ROLE, ROLLED_BACK, ROLLBACK_FAILED and CFG_SAVE_REVERT wait for a step only the customer can take (a setting
# pointed at the certificate, the listener checked, cfg-save changed): reported at once, and tried again once a day.
customer_step() { case "$FAIL_CODE" in NO_ROLE|ROLLED_BACK|ROLLBACK_FAILED|CFG_SAVE_REVERT) return 0 ;; esac; return 1; }

# The time of the first failed attempt for the certificate lego holds now, kept across restarts in
# $STATE_DIR/$NAME.failing as "<epoch> <SHA-256> [reported]".
failing_since() {
    local since="" fp=""
    [ -r "$STATE_DIR/$NAME.failing" ] && read -r since fp _ < "$STATE_DIR/$NAME.failing"
    if [[ $since =~ ^[0-9]+$ ]] && [ "$fp" = "${LEAF_FP:-none}" ]; then printf '%s' "$since"; return; fi
    since=$(date +%s)
    printf '%s %s\n' "$since" "${LEAF_FP:-none}" > "$STATE_DIR/$NAME.failing"
    printf '%s' "$since"
}

failure_report_due() {
    local last_time last_code
    [ -r "$STATE_DIR/$NAME.failure" ] || return 0
    read -r last_time last_code < "$STATE_DIR/$NAME.failure"
    [ "$last_code" != "$FAIL_CODE" ] || [ $(( $(date +%s) - ${last_time:-0} )) -ge 86400 ]
}

# When the next attempts come, from the real waits starting at RETRY_WAITS[$1]: "It is checked again in 1 minute,
# and then after 2, 5, 10 and 30 minutes and every hour."
retry_schedule() {
    local i=$1 last=${RETRY_WAITS[-1]} first later=() every text minutes
    if customer_step; then printf 'It is checked again in a day and then once a day, or at once when you run the deploy step of the guide again.'; return; fi
    minutes=$(( (last + 59) / 60 ))
    if [ "$last" = 3600 ]; then every="every hour"; else every="every $minutes minutes"; fi
    first=${RETRY_WAITS[$i]:-$last}
    if [ "$first" -ge "$last" ]; then
        if [ "$last" = 3600 ]; then printf 'It is checked again in an hour, and then every hour.'; else printf 'It is checked again in %s minutes, and then %s.' "$minutes" "$every"; fi
        return
    fi
    minutes=$(( (first + 59) / 60 ))
    text="It is checked again in $minutes minute"
    [ "$minutes" = 1 ] || text="${text}s"
    for (( i = i + 1; i < ${#RETRY_WAITS[@]} - 1; i++ )); do later+=("$(( (RETRY_WAITS[i] + 59) / 60 ))"); done
    case ${#later[@]} in
        0) printf '%s, and then %s.' "$text" "$every" ;;
        1) printf '%s, and then after %s minutes and %s.' "$text" "${later[0]}" "$every" ;;
        *) printf '%s, and then after %s and %s minutes and %s.' "$text" "$(comma_list "${later[@]:0:${#later[@]}-1}")" "${later[-1]}" "$every" ;;
    esac
}

# The wait between two attempts. deploy and lego's hook ask for the next attempt now (request_attempt), so a step the
# customer took (the guide run again with another account or address, a certificate pointed at by hand) or a new
# certificate is tried at once. A request made during an attempt ends the wait that follows it. The sleep does not hold
# the deployment lock, so a worker that is stopped leaves no lock behind.
retry_sleep() {
    sleep "$1" 9>&- &
    printf '%s %s %s\n' "$BASHPID" "$!" "$SCRIPT_VERSION" > "$STATE_DIR/$NAME.waiting"
    if [ -e "$STATE_DIR/$NAME.again" ]; then
        log "A new attempt was asked for during the last one; it starts now"
        kill "$!" 2> /dev/null
    fi
    wait "$!"
    rm -f "$STATE_DIR/$NAME.waiting"
}

# Asks the background worker for NAME, which holds the lock, for its next attempt now. Returns 0 when that ended its
# wait; otherwise the worker is in an attempt and starts the next one when that attempt ends without success. Only a
# sleep this script's worker started is ended.
#
# A worker of version 1.3.0 or earlier (its wait file names no version) would go on with the script it was started
# from, also after this one was installed. It is stopped here, in its wait, where it has nothing open on FortiGate,
# and request_attempt returns 2: the caller makes the attempt itself, with this script. A worker from 1.4.0 on starts
# the installed script itself before its next attempt (run_worker).
request_attempt() {
    local worker pid version="" ppid
    : > "$STATE_DIR/$NAME.again"
    [ -f "$STATE_DIR/$NAME.waiting" ] || return 1
    read -r worker pid version 2> /dev/null < "$STATE_DIR/$NAME.waiting" || return 1
    [[ $worker =~ ^[0-9]+$ && $pid =~ ^[0-9]+$ ]] || return 1
    [ "$(cat "/proc/$pid/comm" 2> /dev/null)" = sleep ] || return 1
    read -r _ _ _ ppid _ 2> /dev/null < "/proc/$pid/stat" || return 1
    [ "$ppid" = "$worker" ] || return 1
    if [ -z "$version" ]; then
        kill "$worker" 2> /dev/null
        kill "$pid" 2> /dev/null
        rm -f "$STATE_DIR/$NAME.waiting" "$STATE_DIR/$NAME.again"
        log "Stopped the waiting worker of an earlier fairssl-fortigate (process $worker); version $SCRIPT_VERSION goes on from here"
        return 2
    fi
    kill "$pid" 2> /dev/null
}

run_worker() {  # $1 = seconds to wait first, when the first attempt has just failed in the foreground; otherwise 0
    local attempts=0 wait_index=0 wait asked installed last_fp=""
    [[ ${1:-0} =~ ^[0-9]+$ ]] || die "the worker's first wait must be a number of seconds"
    exec 9> "$STATE_DIR/$NAME.lock"
    flock 9
    if [ "${1:-0}" -gt 0 ]; then
        attempts=1 wait_index=1
        # The certificate the foreground attempt failed with ($NAME.failing: "<epoch> <SHA-256> ...").
        read -r _ last_fp _ 2> /dev/null < "$STATE_DIR/$NAME.failing" || last_fp=""
        retry_sleep "$1"
    fi
    while :; do
        # A newer fairssl-fortigate was installed while this worker waited: the attempts go on with it.
        installed=$("$SELF" version 2> /dev/null)
        if [ -n "$installed" ] && [ "$installed" != "fairssl-fortigate $SCRIPT_VERSION" ]; then
            log "$installed is installed now; the deployment goes on with it"
            cleanup_work
            exec "$SELF" worker "$NAME" 0
        fi
        attempts=$((attempts + 1))
        ATTEMPT_NUMBER=$attempts
        # The settings as they are now: setup may have run again during the wait (another account or address).
        if ! load_config; then log "The settings for $NAME are gone ($CONFIG_DIR), so the deployment stops."; return 0; fi
        asked=0
        [ -e "$STATE_DIR/$NAME.again" ] && asked=1
        if attempt_and_report; then break; fi
        # A newer certificate from lego, or an attempt the customer asked for (deploy, after a step taken on FortiGate
        # or setup run again), starts the waits from the first one, as a new job does for Deploy-FortiGate.ps1.
        if [ "$asked" = 1 ] || { [ -n "$last_fp" ] && [ "${LEAF_FP:-}" != "$last_fp" ]; }; then wait_index=0; fi
        last_fp=${LEAF_FP:-}
        flush_outbox
        if [ "$FAIL_CODE" = NOT_SHOWN ]; then log "$FAIL_TEXT $(retry_schedule "$wait_index")"
        else log "Attempt $attempts did not finish ($FAIL_CODE). $(retry_schedule "$wait_index")"; fi
        wait=${RETRY_WAITS[$wait_index]:-${RETRY_WAITS[-1]}}
        customer_step && [ "$wait" -lt "$NO_ROLE_WAIT" ] && wait=$NO_ROLE_WAIT
        [ "$wait_index" -lt $(( ${#RETRY_WAITS[@]} - 1 )) ] && wait_index=$((wait_index + 1))
        retry_sleep "$wait"
    done
    # Keep going until the receiver has every report. The next deployment (lego's next certificate, deploy) may start while
    # this worker still sends them, and one sender is enough: a worker that finds another one sending leaves it to it.
    flock -u 9
    exec 9>&-
    exec 8> "$STATE_DIR/$NAME.outbox.lock"
    flock -n 8 || return 0
    wait_index=0
    until flush_outbox; do
        wait=${RETRY_WAITS[$wait_index]:-${RETRY_WAITS[-1]}}
        [ "$wait_index" -lt $(( ${#RETRY_WAITS[@]} - 1 )) ] && wait_index=$((wait_index + 1))
        sleep "$wait"
    done
}

start_background_worker() {  # $1 = seconds the worker waits before its first attempt
    local unit
    if [ -d /run/systemd/system ] && command -v systemd-run > /dev/null 2>&1; then
        unit="fairssl-fortigate-$(printf '%s' "$NAME" | tr -c 'A-Za-z0-9_-' '_')-$(date +%s)"
        if systemd-run --quiet --collect --unit "$unit" --description "FairSSL FortiGate certificate deployment ($NAME)" \
            "$SELF" worker "$NAME" "$1" > /dev/null 2>&1 \
            || systemd-run --quiet --unit "$unit" "$SELF" worker "$NAME" "$1" > /dev/null 2>&1; then
            say "fairssl-fortigate: the deployment to FortiGate runs in the background as $unit; log: $LOG"
            return 0
        fi
    fi
    setsid "$SELF" worker "$NAME" "$1" < /dev/null >> "$LOG" 2>&1 &
    say "fairssl-fortigate: the deployment to FortiGate runs in the background (process $!); log: $LOG"
}

cmd_hook() {
    require_root
    load_config || die "no settings for '$NAME' in $CONFIG_DIR; run fairssl-fortigate setup first (see FairSSL's guide)"
    open_log
    log "lego saved a certificate for $NAME; starting the deployment to FortiGate"
    if request_attempt; then log "The worker that waited for its next attempt tries again now, with this certificate"; fi
    # The worker started here waits for the lock behind that one, and makes sure this certificate is installed.
    start_background_worker 0
}

# At boot (the @reboot line of the guide's cron file): a deployment that a restart interrupted goes on. Nothing
# starts when FortiGate was seen serving the certificate lego holds and FairSSL has every report.
cmd_resume() {
    local fp
    require_root
    load_config || return 0
    fp=$(cert_sha256 "$LEGO_PATH/certificates/$NAME.crt" 2>/dev/null)
    [ -n "$fp" ] || return 0
    if grep -q -x "$fp" "$STATE_DIR/$NAME.reported" 2>/dev/null && [ ! -e "$STATE_DIR/$NAME.failing" ] \
        && [ -z "$(find "$OUTBOX" "$OLD_OUTBOX" -maxdepth 1 -name '*.json' 2>/dev/null)" ]; then
        return 0
    fi
    open_log
    log "This server restarted before the deployment of $NAME finished; it goes on"
    start_background_worker "${RETRY_WAITS[0]}"
}

cmd_worker() {
    require_root
    load_config || die "no settings for '$NAME' in $CONFIG_DIR"
    open_log
    run_worker "${1:-0}"
}

cmd_deploy() {
    local asked wait
    require_root
    load_config || die "no settings for '$NAME' in $CONFIG_DIR; run fairssl-fortigate setup first"
    open_log
    exec 9> "$STATE_DIR/$NAME.lock"
    if ! flock -n 9; then
        request_attempt; asked=$?
        if [ "$asked" = 0 ]; then
            log "deploy: the worker that waited for its next attempt tries again now"
            say "The deployment for $NAME that waited in the background for its next attempt tries again now, with the settings as they are. Follow it with: sudo tail -f $LOG"
            return 0
        fi
        # After an earlier version's waiting worker was stopped, its lock is free as soon as the process is gone.
        if [ "$asked" != 2 ] || ! flock -w "$SILENCE_LIMIT" 9; then
            : > "$STATE_DIR/$NAME.again"
            say "A deployment for $NAME is already running in the background; if its current attempt does not install the certificate, it tries again at once with the settings as they are. Follow it with: sudo tail -f $LOG"
            return 0
        fi
    fi
    FOREGROUND=1
    if attempt_and_report; then
        flush_outbox || start_background_worker 0 > /dev/null
        say "Done: FortiGate serves the certificate. Renewals are installed the same way, without you."
        return 0
    fi
    flush_outbox
    exec 9>&-
    say ""
    if [ "$FAIL_CODE" = NOT_SHOWN ]; then say "$FAIL_TEXT"; else say "The certificate is not installed yet ($FAIL_CODE). The reason is above and in the report."; fi
    # A step only the customer can take is checked again in a day, as retry_schedule says.
    wait=${RETRY_WAITS[0]}
    customer_step && [ "$wait" -lt "$NO_ROLE_WAIT" ] && wait=$NO_ROLE_WAIT
    start_background_worker "$wait"
    say "$(retry_schedule 0) This goes on until it works."
    return 1
}

cmd_status() {
    local file
    require_root
    load_config || die "no settings for '$NAME' in $CONFIG_DIR"
    say "FortiGate:   $FGT_USER@$FGT_HOST port $FGT_PORT"
    say "Certificate: $LEGO_PATH/certificates/$NAME.crt"
    say "Reports to:  ${REPORT_URL:-nowhere, no report address is set} (renewal id $RENEWAL_ID)"
    say "Last result: $(cat "$STATE_DIR/$NAME.result" 2>/dev/null || echo none)"
    file=$(find "$OUTBOX" "$OLD_OUTBOX" -maxdepth 1 -name "*.json" 2>/dev/null | wc -l)
    say "Reports waiting to be sent: $file"
    say ""
    tail -n 40 "$LOG_DIR/$NAME.log" 2>/dev/null
}

cmd_setup() {
    local host="" port=22 user="admin" report_url="" lego_path=/etc/ssl/fortigate renewal_id="" password=""
    local old_fp new_fp report_url_given=""
    # "shift 2 || shift": an option given last without its value is taken as empty, and the loop ends.
    while [ $# -gt 0 ]; do
        case "$1" in
            --name) NAME=${2:-}; shift 2 || shift ;;
            --host) host=${2:-}; shift 2 || shift ;;
            --port) port=${2:-}; shift 2 || shift ;;
            --user) user=${2:-}; shift 2 || shift ;;
            --report-url) report_url=${2:-}; report_url_given=1; shift 2 || shift ;;
            --lego-path) lego_path=${2:-}; shift 2 || shift ;;
            *) die "unknown option '$1'" ;;
        esac
    done
    require_root
    valid_name "$NAME" || die "--name must be the certificate name from the guide"
    if ! [[ $host =~ ^[A-Za-z0-9._:-]+$ ]] || [ "$host" = YOUR_FORTIGATE_IP ]; then
        die "--host must be FortiGate's IP address or host name (replace YOUR_FORTIGATE_IP)"
    fi
    [[ $port =~ ^[0-9]+$ ]] || die "--port must be a number"
    [[ $user =~ ^[A-Za-z0-9._@-]+$ ]] || die "--user must be a FortiGate administrator name"
    # Setup again without --report-url keeps the address this certificate reports to; --report-url "" turns it off.
    if [ -z "$report_url_given" ] && [ -r "$(config_file "$NAME")" ]; then
        report_url=$(sed -n 's/^REPORT_URL=//p' "$(config_file "$NAME")" | head -n 1)
    fi
    [ -z "$report_url" ] || [[ $report_url =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?/[A-Za-z0-9/._-]*$ ]] || die "--report-url must be an https address"
    [[ $lego_path =~ ^/[A-Za-z0-9/._-]+$ ]] || die "--lego-path must be an absolute path"
    for tool in ssh ssh-keyscan ssh-keygen openssl curl flock setsid timeout; do
        command -v "$tool" > /dev/null 2>&1 || die "$tool is missing; run step 1 of the guide again"
    done

    mkdir -p "$CONFIG_DIR" "$lego_path" && chmod 0700 "$CONFIG_DIR" "$lego_path"
    # lego's --http.webroot must exist before the first issuance.
    install -d -m 0755 "${FAIRSSL_FORTIGATE_WEBROOT:-/var/www/html}"
    open_log

    if [ -t 0 ]; then
        IFS= read -r -s -p "Password for $user on FortiGate $host: " password || die "no password given"
        printf '\n'
    else
        IFS= read -r password || [ -n "$password" ] || die "no password on standard input"
    fi
    [ -n "$password" ] || die "the password is empty"
    PASSWORD_FILE=$(password_file "$NAME")
    ( umask 077; printf '%s' "$password" > "$PASSWORD_FILE.tmp" ) && mv -f "$PASSWORD_FILE.tmp" "$PASSWORD_FILE"
    chmod 0600 "$PASSWORD_FILE"
    password=""

    if [ -r "$(config_file "$NAME")" ]; then
        renewal_id=$(sed -n 's/^RENEWAL_ID=//p' "$(config_file "$NAME")")
    fi
    [[ $renewal_id =~ ^[0-9a-f-]{36}$ ]] || renewal_id=$(cat /proc/sys/kernel/random/uuid)
    {
        printf 'FGT_HOST=%s\nFGT_PORT=%s\nFGT_USER=%s\nRENEWAL_ID=%s\nREPORT_URL=%s\nLEGO_PATH=%s\n' \
            "$host" "$port" "$user" "$renewal_id" "$report_url" "$lego_path"
        if [ -n "${https_proxy:-${HTTPS_PROXY:-}}" ]; then printf 'REPORT_PROXY=%s\n' "${https_proxy:-${HTTPS_PROXY:-}}"; fi
    } > "$(config_file "$NAME").tmp" && mv -f "$(config_file "$NAME").tmp" "$(config_file "$NAME")"
    load_config || die "could not write the settings in $CONFIG_DIR"

    # Pin FortiGate's SSH host key. Running setup again pins the key FortiGate has now.
    new_work_dir
    touch "$KNOWN_HOSTS"
    ssh-keyscan -T "$SILENCE_LIMIT" -p "$port" "$host" 2> /dev/null | grep -v '^#' > "$WORK/keys"
    [ -s "$WORK/keys" ] || die "FortiGate $host does not answer SSH on port $port. Check the address, the port and that SSH is allowed on the interface (Administrative Access)"
    old_fp=$(ssh-keygen -F "$(known_hosts_key)" -f "$KNOWN_HOSTS" 2> /dev/null | grep -v '^#' | ssh-keygen -l -f - 2> /dev/null | awk '{print $2}' | sort -u | tr '\n' ' ')
    ssh-keygen -R "$(known_hosts_key)" -f "$KNOWN_HOSTS" > /dev/null 2>&1
    cat "$WORK/keys" >> "$KNOWN_HOSTS"
    rm -f "$KNOWN_HOSTS.old"
    chmod 0600 "$KNOWN_HOSTS"
    new_fp=$(ssh-keygen -l -f "$WORK/keys" 2> /dev/null | awk '{print $2}' | sort -u | tr '\n' ' ')
    if [ -n "$old_fp" ] && [ "$old_fp" != "$new_fp" ]; then
        say "FortiGate's SSH host key changed from $old_fp to $new_fp; the new key is pinned."
    else
        say "FortiGate's SSH host key is pinned: $new_fp"
    fi

    if [ -f "$OLD_SCRIPT" ]; then
        rm -f "$OLD_SCRIPT" && say "Removed FairSSL's earlier deploy script $OLD_SCRIPT, which held the FortiGate password."
    fi

    FOREGROUND=1
    : > "$WORK/attempt.log"
    if ! detect; then
        say ""
        die "setup could not finish: $FAIL_TEXT"
    fi
    say ""
    say "Ready. Settings: $(config_file "$NAME") (the password is in $PASSWORD_FILE, readable by root only)."
}

usage() {
    sed -n '2,13p' "$SELF" | sed 's/^# \{0,1\}//'
    exit "${1:-0}"
}

command=${1:-}
[ $# -gt 0 ] && shift
case "$command" in
    setup) cmd_setup "$@" ;;
    hook|resume|worker|deploy|status)
        NAME=${1:-}
        valid_name "$NAME" || die "give the certificate name from the guide, for example: fairssl-fortigate $command example.com"
        shift
        "cmd_$command" "$@" ;;
    version|--version) say "fairssl-fortigate $SCRIPT_VERSION" ;;
    help|-h|--help) usage 0 ;;
    *) usage 1 ;;
esac
