#!/bin/bash
# Copyright 2026 FairSSL A/S - fairssl.dk, fairssl.se, sslbrain.com
# File and guide: https://sslbrain.com/scripts/fortimail-linux/
# Installs on: FortiMail
#
# 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 FortiMail, over SSH, and keeps trying until it is
#   installed. Reports every result when it has a report address.
# .DESCRIPTION
#   Used by FairSSL's guide "FortiMail (Linux Agent)" and, with any ACME service, as lego's deploy hook.
#
#   fairssl-fortimail setup  --name NAME --host ADDRESS [--port 22] [--user admin] [--report-url URL]
#       Asks for the FortiMail password and keeps it in /etc/fairssl-fortimail/NAME.password (root only, 0600),
#       pins FortiMail's SSH host key in /etc/fairssl-fortimail/known_hosts, logs in once and shows what it found.
#   fairssl-fortimail deploy NAME   Installs the certificate now and shows the result. If the attempt fails, a
#                                   background worker keeps trying.
#   fairssl-fortimail hook NAME     lego's --deploy-hook: starts the background worker and returns at once.
#   fairssl-fortimail resume NAME   At boot: starts the worker again when a restart interrupted a deployment.
#   fairssl-fortimail 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 FortiMail 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), uploads the certificate with its intermediates as a local certificate named
# fssl-<6 hex of the certificate name>-<12 hex of the certificate's SHA-256>, makes it FortiMail's default
# certificate (HTTPS, webmail and mail over TLS), reloads httpd and smtpd, and looks with TLS handshakes on HTTPS
# and SMTP (STARTTLS) at what it serves; the default certificate read back over SSH decides. If a listener that answered
# before stops answering, the previous certificate is put back. It keeps the previous certificate object and deletes
# older objects of its own. A failed attempt is reported and tried again after 1, 2, 5, 15, 30 and then every 60
# minutes, for as long as it takes, also after a restart of this server. Every result is sent to the report address (a failure
# that repeats unchanged once a day); a report the receiver has not confirmed waits in /var/lib/fairssl-fortimail/outbox
# and is sent again.
#
# 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: FortiMail's IP address or host name.
# .PARAMETER --port
#   setup: FortiMail's SSH port. Defaults to 22.
# .PARAMETER --user
#   setup: the FortiMail administrator the script logs in as. Defaults to admin.
# .PARAMETER --https-port
#   setup: FortiMail's HTTPS port for the TLS check. Defaults to 443.
# .PARAMETER --smtp-port
#   setup: FortiMail's SMTP port for the TLS check (STARTTLS). Defaults to 25.
# .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/fortimail.

# 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_FORTIMAIL_ASKPASS_FILE:-}" ]; then
    cat -- "$FAIRSSL_FORTIMAIL_ASKPASS_FILE"
    exit
fi

SCRIPT_VERSION="1.2.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_FORTIMAIL_CONFIG_DIR:-/etc/fairssl-fortimail}
STATE_DIR=${FAIRSSL_FORTIMAIL_STATE_DIR:-/var/lib/fairssl-fortimail}
LOG_DIR=${FAIRSSL_FORTIMAIL_LOG_DIR:-/var/log/fairssl-fortimail}
KNOWN_HOSTS="$CONFIG_DIR/known_hosts"
OUTBOX="$STATE_DIR/outbox"
OLD_SCRIPT=/usr/local/bin/fairssl-fortimail-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_FORTIMAIL_SILENCE_LIMIT:-300}
# Waits between attempts in seconds; the last one repeats with no end.
read -r -a RETRY_WAITS <<< "${FAIRSSL_FORTIMAIL_RETRY_WAITS:-60 120 300 900 1800 3600}"
# How long FortiMail gets to start serving the new default certificate after the reload.
SWITCH_WAIT=${FAIRSSL_FORTIMAIL_SWITCH_WAIT:-300}
SWITCH_POLL=${FAIRSSL_FORTIMAIL_SWITCH_POLL:-10}
# A certificate FortiMail could not serve without a service going dark is tried again after a day, not every hour:
# each try switches and reloads httpd and smtpd on a working mail gateway. A new certificate from lego goes at once.
STOPPED_WAIT=${FAIRSSL_FORTIMAIL_STOPPED_WAIT:-86400}
# How often a waiting worker looks for a new certificate from lego.
WAKE_POLL=${FAIRSSL_FORTIMAIL_WAKE_POLL:-60}
# The services that pick up a new default certificate on reload (FortiMail's own guidance: httpd and smtpd).
RELOAD_SERVICES=(httpd smtpd)

FOREGROUND=0
NAME=""
LOG=/dev/null
WORK=""

say() { printf '%s\n' "$*"; }
log() {
    local line
    line="$(date -u +%Y-%m-%dT%H:%M:%SZ) $*"
    printf '%s\n' "$line" >> "$LOG"
    if [ -n "$WORK" ]; then printf '%s\n' "$line" >> "$WORK/attempt.log"; fi
    if [ "$FOREGROUND" = 1 ]; then printf '%s\n' "$*"; fi
}
die() { printf 'fairssl-fortimail: %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
    FML_HOST="" FML_PORT=22 FML_USER="" RENEWAL_ID="" REPORT_URL="" LEGO_PATH=/etc/ssl/fortimail REPORT_PROXY=""
    HTTPS_PORT=443 SMTP_PORT=25
    while IFS='=' read -r key value; do
        case "$key" in
            FML_HOST) FML_HOST=$value ;;
            FML_PORT) FML_PORT=$value ;;
            FML_USER) FML_USER=$value ;;
            HTTPS_PORT) HTTPS_PORT=$value ;;
            SMTP_PORT) SMTP_PORT=$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")
    [ -n "$FML_HOST" ] && [ -n "$FML_USER" ] && [ -r "$PASSWORD_FILE" ]
}

open_log() {
    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-fortimail.XXXXXX") || die "cannot create a temporary folder"
}
cleanup_work() { [ -n "$WORK" ] && rm -rf "$WORK"; }
trap cleanup_work EXIT

# ---------------------------------------------------------------------------------------------------------------
# SSH to FortiMail. The commands go to ssh's standard input as a batch, the form FortiMail's CLI takes without a
# terminal. A refused command is answered with text, so every result is read back from FortiMail's state or checked
# on the wire, and FortiMail's own words are only used to explain a failure.
# ---------------------------------------------------------------------------------------------------------------
FAIL_CODE=""
FAIL_TEXT=""
fail() { FAIL_CODE=$1; FAIL_TEXT=$2; log "$1: $2"; return 1; }

# An older FortiMail may sign 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 FortiMail 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.
fml() {
    [ -n "${HOSTKEY_PROBED:-}" ] || host_key_options
    local batch=$1 pid 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-fortimail}" \
        FAIRSSL_FORTIMAIL_ASKPASS_FILE="$PASSWORD_FILE" \
        setsid ssh -T -p "$FML_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 \
        -- "$FML_USER@$FML_HOST" < "$batch" > "$WORK/out" 2> "$WORK/err" &
    pid=$!
    quiet_since=$(date +%s)
    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 SILENT "FortiMail $FML_HOST:$FML_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=$(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 "FortiMail $FML_HOST:$FML_PORT answered with another SSH host key than the one pinned at setup. If FortiMail was replaced or reinstalled, run: sudo fairssl-fortimail setup --name $NAME --host $FML_HOST --port $FML_PORT --user $FML_USER"
            else
                fail HOSTKEY_UNKNOWN "no SSH host key is pinned for $FML_HOST:$FML_PORT; run fairssl-fortimail setup again"
            fi ;;
        *"no matching host key type found"*)
            fail HOSTKEY_TYPE "FortiMail $FML_HOST:$FML_PORT signs its SSH host key only with SHA-1 (ssh-rsa), and this server's system policy refuses that ($err). Update FortiMail, 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 "FortiMail refused the login of '$FML_USER'. If the password was changed, run fairssl-fortimail 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 UNREACHABLE "cannot reach FortiMail on $FML_HOST:$FML_PORT ($err)" ;;
        *)
            fail SSH_FAILED "ssh to $FML_HOST:$FML_PORT ended with exit code $1 ($err)" ;;
    esac
}

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

# FortiMail's answer, for the log: refusals and errors only, never a line that could carry key material.
fml_answer() {
    cat "$WORK/err" "$WORK/out" | tr -d '\r' \
        | grep -E 'Command fail|Return code|Error string|error|Error|invalid|Invalid|not |duplicated|Unknown action|unknown command|MUST|too long|denied|fail' \
        | grep -v -E 'PRIVATE|BEGIN|END|[A-Za-z0-9+/=]{20,}' | sed -E 's/^.*[#$] //' | sort -u | head -n 8 | tr '\n' ' '
}

# The value of "key : value" in a "get" output.
fml_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 } }'
}

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

# ---------------------------------------------------------------------------------------------------------------
# The certificate on disk.
# ---------------------------------------------------------------------------------------------------------------
read_certificate() {
    local bundle=$LEGO_PATH/certificates/$NAME.crt key=$LEGO_PATH/certificates/$NAME.key i
    if [ ! -s "$bundle" ] || [ ! -s "$key" ]; then
        fail CERT_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 CERT_MISSING "$bundle holds no readable certificate"
        return 1
    fi
    LEAF_FP=$(cert_sha256 "$LEAF_FILE")
    # An expired certificate, one that is not valid yet and an Ed25519 one are refused by browsers and mail servers,
    # so they are not installed. 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
    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 clients refuse it. lego's next renewal brings a new one"
        return 1
    fi
    key_type=$(openssl x509 -in "$LEAF_FILE" -noout -text | sed -n 's/^[[:space:]]*Public Key Algorithm:[[:space:]]*//p' | head -n 1)
    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 and mail servers 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
    LEAF_SHA1=$(openssl x509 -in "$LEAF_FILE" -noout -fingerprint -sha1 | sed 's/.*=//; s/://g' | tr 'a-f' 'A-F')
    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=$(openssl x509 -in "$LEAF_FILE" -noout -text | grep -o 'DNS:[^,]*' | head -n 1 | sed 's/^DNS://; s/[[:space:]]*$//')
    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)
    OBJECT="fssl-$(id6)-${LEAF_FP:0:12}"
    return 0
}

# 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'; }
id6() { printf '%s' "$NAME" | sha256sum | cut -c1-6; }

# The objects this script made for this certificate, oldest first. FortiMail's certificate listing is not read:
# the script deletes only names it wrote down itself.
objects_file() { printf '%s/%s.objects' "$STATE_DIR" "$NAME"; }
own_object() { [[ $1 =~ ^fssl-$(id6)-[0-9a-f]{12}$ ]]; }
remember_object() {
    grep -q -x -F -- "$1" "$(objects_file)" 2>/dev/null || printf '%s\n' "$1" >> "$(objects_file)"
}

# ---------------------------------------------------------------------------------------------------------------
# What FortiMail has now.
# ---------------------------------------------------------------------------------------------------------------
detect() {
    log "Connecting to FortiMail $FML_HOST port $FML_PORT as $FML_USER"
    printf 'get system status\n' > "$WORK/batch"
    fml "$WORK/batch" || return 1
    if fml_refused && ! grep -q 'Version' "$WORK/out"; then
        fail NO_RIGHTS "the FortiMail account '$FML_USER' may not run CLI commands: $(fml_answer)"
        return 1
    fi
    FML_VERSION=$(fml_value Version)
    read_default || return 1
    log "FortiMail: ${FML_VERSION:-version not readable with this account}; default certificate: '${DEFAULT_CERT:-not readable}'"
    return 0
}

# Sets DEFAULT_CERT from "show system global" (set default-certificate "NAME"), or from a "get" form.
read_default() {
    printf 'show system global\n' > "$WORK/batch"
    fml "$WORK/batch" || return 1
    DEFAULT_CERT=$(tr -d '\r' < "$WORK/out" | sed -n -E 's/^[[:space:]]*set default-certificate "?([^"]*)"?[[:space:]]*$/\1/p' | head -n 1)
    [ -n "$DEFAULT_CERT" ] || DEFAULT_CERT=$(fml_value default-certificate)
    return 0
}

# ---------------------------------------------------------------------------------------------------------------
# TLS: what FortiMail serves on HTTPS ($HTTPS_PORT) and SMTP with STARTTLS ($SMTP_PORT). Sets SERVED_FP and
# SERVED_CHAIN (SHA-256 of the certificates after the leaf). Returns 1 when no handshake was possible.
# ---------------------------------------------------------------------------------------------------------------
served() {
    local port=$1 sni=${LEAF_CN/#\*./fairssl-check.} target f starttls=()
    SERVED_FP="" SERVED_CHAIN=""
    if [[ $FML_HOST == *:* ]]; then target="[$FML_HOST]:$port"; else target="$FML_HOST:$port"; fi
    [ "$port" = "$SMTP_PORT" ] && starttls=(-starttls smtp)
    timeout "$SILENCE_LIMIT" openssl s_client -connect "$target" "${starttls[@]}" -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 the port serves the new certificate. 0 = served with its chain, 2 = leaf without its chain,
# 3 = another certificate, 4 = no handshake. $2 = 0 when a handshake worked before the switch; a listener that
# could not be reached before is not waited for.
await_served() {
    local port=$1 before=${2:-4} waited=0 result=4
    while :; do
        if served "$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, make default, reload, verify, clean up.
# ---------------------------------------------------------------------------------------------------------------
attempt() {
    local https_before=4 smtp_before=4 https_old="" smtp_old="" https_result smtp_result
    FAIL_CODE="" FAIL_TEXT="" VERIFIED_HOW="" LEAF_FP=""
    read_certificate || return 1
    log "Certificate: $LEAF_CN, SHA-256 ${LEAF_FP:0:16}..., expires $LEAF_EXPIRY, ${#CHAIN_FILES[@]} intermediate(s); FortiMail object $OBJECT"
    detect || return 1
    PREVIOUS=$DEFAULT_CERT

    # A service that answers now and not after the change is a fault the change made.
    served "$HTTPS_PORT" && { https_before=0; https_old=$SERVED_FP; }
    served "$SMTP_PORT" && { smtp_before=0; smtp_old=$SERVED_FP; }

    if [ "$DEFAULT_CERT" = "$OBJECT" ]; then
        log "FortiMail already uses '$OBJECT' as its default certificate"
        # An earlier attempt may have ended before the reload.
        if { [ "$https_before" = 0 ] && [ "$https_old" != "$LEAF_FP" ]; } || { [ "$smtp_before" = 0 ] && [ "$smtp_old" != "$LEAF_FP" ]; }; then
            reload_services
        fi
    else
        upload || return 1
        set_default "$OBJECT" || return 1
        reload_services
    fi

    await_served "$HTTPS_PORT" "$https_before"; https_result=$?
    await_served "$SMTP_PORT" "$smtp_before"; smtp_result=$?
    verify_result HTTPS "$HTTPS_PORT" "$https_result" "$https_before" || return 1
    verify_result SMTP "$SMTP_PORT" "$smtp_result" "$smtp_before" || return 1

    if [ "$https_result" = 2 ] || [ "$smtp_result" = 2 ]; then
        # FortiMail sends the intermediates appended to the local certificate. One that sends only the leaf gets
        # them in its CA store as well, and one more reload.
        ca_store_upload
        reload_services
        # Checked again like the first time: a service that answered then must answer now with the whole chain.
        [ "$https_result" = 4 ] || https_before=0
        [ "$smtp_result" = 4 ] || smtp_before=0
        VERIFIED_HOW=""
        await_served "$HTTPS_PORT" "$https_before"; https_result=$?
        await_served "$SMTP_PORT" "$smtp_before"; smtp_result=$?
        verify_result HTTPS "$HTTPS_PORT" "$https_result" "$https_before" || return 1
        verify_result SMTP "$SMTP_PORT" "$smtp_result" "$smtp_before" || return 1
        if [ "$https_result" = 2 ] || [ "$smtp_result" = 2 ]; then
            # TLS is information (owner 20-11-2026): the certificate is installed, and the note says what clients see.
            log "Note: FortiMail serves the new certificate without its intermediate certificate, also after it was added to the CA store, so some clients may not trust it"
        fi
    fi
    if [ -z "$VERIFIED_HOW" ]; then
        [ "$DEFAULT_CERT" = "$OBJECT" ] || { fail NOT_VERIFIED "neither HTTPS nor SMTP on $FML_HOST answered TLS from this server, and FortiMail's default certificate could not be read back"; return 1; }
        VERIFIED_HOW="default certificate (configuration)"
    fi

    cleanup_objects
    return 0
}

upload_batch() {  # $@ = intermediate files to send with the leaf
    {
        printf 'config system certificate local\n'
        printf 'edit "%s"\n' "$OBJECT"
        printf 'set private-key "%s"\n' "$(tr -d '\r' < "$KEY_FILE")"
        printf 'set certificate "%s"\n' "$(cat "$LEAF_FILE" "$@" | tr -d '\r')"
        printf 'end\n'
    } > "$WORK/batch"
}

# The intermediates go up with the leaf, in one "set certificate": FortiMail serves a local certificate's chain from
# what was imported with it. A FortiMail that refuses that gets the leaf alone and the intermediates in its CA store.
upload() {
    remember_object "$OBJECT"
    upload_batch "${CHAIN_FILES[@]}"
    log "Uploading the certificate$( [ ${#CHAIN_FILES[@]} -gt 0 ] && echo " with ${#CHAIN_FILES[@]} intermediate(s)") as '$OBJECT'"
    fml "$WORK/batch" || { rm -f "$WORK/batch"; return 1; }
    rm -f "$WORK/batch"
    UPLOAD_ANSWER=$(fml_answer)
    if fml_refused && [ ${#CHAIN_FILES[@]} -gt 0 ]; then
        log "FortiMail did not take the certificate with its intermediates ($UPLOAD_ANSWER); uploading the certificate alone"
        upload_batch
        fml "$WORK/batch" || { rm -f "$WORK/batch"; return 1; }
        rm -f "$WORK/batch"
        UPLOAD_ANSWER=$(fml_answer)
        ca_store_upload
    fi
    [ -n "$UPLOAD_ANSWER" ] && log "FortiMail noted: $UPLOAD_ANSWER"
    return 0
}

# Points FortiMail's default certificate at $1 and reads it back. A name FortiMail does not hold is refused, so the
# read-back also proves the upload.
set_default() {
    local answer
    printf 'config system global\nset default-certificate "%s"\nend\n' "$1" > "$WORK/batch"
    log "Making '$1' FortiMail's default certificate (was '${DEFAULT_CERT:-not readable}')"
    fml "$WORK/batch" || return 1
    answer=$(fml_answer)
    read_default || return 1
    if [ -n "$DEFAULT_CERT" ] && [ "$DEFAULT_CERT" != "$1" ]; then
        fail DEFAULT_REFUSED "FortiMail still uses '$DEFAULT_CERT' as its default certificate after setting '$1'. FortiMail answered: ${answer:-nothing}${UPLOAD_ANSWER:+; to the upload: $UPLOAD_ANSWER}"
        return 1
    fi
    [ -n "$DEFAULT_CERT" ] || log "FortiMail's default certificate could not be read back; the TLS check decides"
    return 0
}

# Restarts the services that serve the default certificate. FortiMail asks to confirm; the "y" answers it. A refused
# reload is logged and is not a failure by itself: the default certificate read back over SSH decides, and TLS
# afterwards is information (owner 20-11-2026).
reload_services() {
    local service
    for service in "${RELOAD_SERVICES[@]}"; do
        printf 'execute reload %s\ny\n' "$service" > "$WORK/batch"
        if fml "$WORK/batch"; then
            log "Reloaded $service$( [ -n "$(fml_answer)" ] && echo " (FortiMail answered: $(fml_answer))")"
        else
            log "The reload of $service did not finish: $FAIL_TEXT"
            FAIL_CODE="" FAIL_TEXT=""
        fi
    done
}

verify_result() {  # $1 label, $2 port, $3 await result, $4 handshake before (0 ok)
    case "$3" in
        0) log "$1 on port $2 serves the new certificate with its intermediate(s)"; VERIFIED_HOW="${VERIFIED_HOW:+$VERIFIED_HOW, }$1 (TLS)"; return 0 ;;
        2) log "$1 on port $2 serves the new certificate, but without its intermediate(s)"; VERIFIED_HOW="${VERIFIED_HOW:+$VERIFIED_HOW, }$1 (TLS)"; return 0 ;;
        3)
            # TLS is information; FortiMail's configuration read over SSH decides (owner 20-11-2026).
            if [ "$DEFAULT_CERT" = "$OBJECT" ]; then
                log "$1 on port $2 still serves another certificate (SHA-256 ${SERVED_FP:0:16}...) ${SWITCH_WAIT} seconds after the change; FortiMail's default certificate is '$OBJECT', so the configuration decides"
                VERIFIED_HOW="${VERIFIED_HOW:+$VERIFIED_HOW, }$1 (configuration)"
                return 0
            fi
            fail NOT_VERIFIED "$1 on $FML_HOST:$2 still serves another certificate (SHA-256 ${SERVED_FP:0:16}...) ${SWITCH_WAIT} seconds after '$OBJECT' became the default certificate, and FortiMail's default certificate does not read back as '$OBJECT'"; return 1 ;;
        4)
            if [ "$4" = 0 ]; then
                if rollback; then
                    fail ROLLED_BACK "$1 on $FML_HOST:$2 stopped answering TLS after the switch to '$OBJECT', so the previous certificate was put back"
                else
                    fail TLS_STOPPED "$1 on $FML_HOST:$2 stopped answering TLS after the reload, and there was no other default certificate to put back"
                fi
                return 1
            fi
            log "$1 on port $2 cannot be reached from this server; it is not checked"
            return 0 ;;
    esac
}

# Puts the previous default certificate back; fails when there is none, or FortiMail could not be reached for it.
rollback() {
    [ -n "$PREVIOUS" ] && [ "$PREVIOUS" != "$OBJECT" ] || return 1
    printf 'config system global\nset default-certificate "%s"\nend\n' "$PREVIOUS" > "$WORK/batch"
    fml "$WORK/batch" || return 1
    reload_services
    log "'$PREVIOUS' is FortiMail's default certificate again"
}

# Offers each intermediate to FortiMail's CA store. FortiMail answers "Found duplicated CA" for one it holds
# (measured at a customer, 31-10-2026); whatever it answers is never an error, the TLS check decides.
ca_store_upload() {
    local f fp
    for f in "${CHAIN_FILES[@]}"; do
        fp=$(cert_sha256 "$f")
        { printf 'config system certificate ca\nedit "fssl-ca-%s"\nset certificate "' "${fp:0:12}"; tr -d '\r' < "$f"; printf '"\nend\n'; } > "$WORK/batch"
        fml "$WORK/batch" || { FAIL_CODE="" FAIL_TEXT=""; return 0; }
        if grep -q -i 'duplicated CA' "$WORK/out" "$WORK/err"; then
            log "FortiMail's CA store already holds intermediate ${fp:0:12}"
        else
            log "Offered intermediate ${fp:0:12} to FortiMail's CA store as fssl-ca-${fp:0:12}$( [ -n "$(fml_answer)" ] && echo "; FortiMail answered: $(fml_answer)")"
        fi
    done
}

# Keeps the new object and the previous default; deletes the other objects this script made for this certificate.
# One delete per session, so a refusal (an object another setting still uses) keeps only that one for next time.
cleanup_objects() {
    local name keep=" $OBJECT $PREVIOUS ${DEFAULT_CERT:-} " remaining=()
    [ -r "$(objects_file)" ] || return 0
    while IFS= read -r name; do
        [ -n "$name" ] || continue
        if [[ $keep == *" $name "* ]] || ! own_object "$name"; then remaining+=("$name"); continue; fi
        printf 'config system certificate local\ndelete "%s"\nend\n' "$name" > "$WORK/delete"
        if ! fml "$WORK/delete"; then
            FAIL_CODE="" FAIL_TEXT=""
            remaining+=("$name")
        elif fml_refused && ! grep -q -i -E 'not found|not exist' "$WORK/out" "$WORK/err"; then
            log "Kept '$name': FortiMail would not delete it ($(fml_answer)); it is tried again at the next renewal"
            remaining+=("$name")
        else
            log "Deleted the older certificate object '$name'"
        fi
    done < "$(objects_file)"
    printf '%s\n' "${remaining[@]}" > "$(objects_file).tmp" && mv -f "$(objects_file).tmp" "$(objects_file)"
}

# ---------------------------------------------------------------------------------------------------------------
# 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"
}

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, $2 error code, $3 error text
    local kid file text excerpt lego_version
    # 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
    text=""
    [ -n "$2" ] && text="$2: $3"
    excerpt=$(tail -c 20000 "$WORK/attempt.log" 2>/dev/null)
    lego_version=$(lego --version 2>/dev/null | sed -n 's/^lego version \([^ ]*\).*/\1/p')
    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")"
        printf '"install_status":%s,' "$(json_string "$1")"
        if [ -n "$2" ]; then
            printf '"install_error_code":%s,' "$(json_string "$2")"
            printf '"install_error_string":%s,' "$(json_string "${text: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 "fortimail-$SCRIPT_VERSION")"
        printf '"meta":{"guide":"fortimail-linux","certificate_name":%s,"fortimail_object":%s,"fortimail":%s,"verified":%s,"log":%s}' \
            "$(json_string "$NAME")" "$(json_string "${OBJECT:-}")" "$(json_string "${FML_VERSION:-}")" \
            "$(json_string "${VERIFIED_HOW:-}")" "$(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 "$OUTBOX"/*.json; do
        [ -e "$file" ] || return 0
        # 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-fortimail/$SCRIPT_VERSION" --data-binary "@$file" "$REPORT_URL" 2>&1)
        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.
            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 FortiMail serves the certificate.
attempt_and_report() {
    rotate_log
    new_work_dir
    : > "$WORK/attempt.log"
    PREVIOUS="" UPLOAD_ANSWER=""
    if attempt; then
        log "Installed and verified: $LEAF_CN on FortiMail $FML_HOST as '$OBJECT' (${VERIFIED_HOW})"
        record_result "installed $OBJECT ($LEAF_CN, ${LEAF_FP:0:12}): ${VERIFIED_HOW}"
        if ! reported_before; then
            queue_report success "" ""
            printf '%s\n' "$LEAF_FP" >> "$STATE_DIR/$NAME.reported"
        fi
        rm -f "$STATE_DIR/$NAME.failure"
        return 0
    fi
    record_result "failed $FAIL_CODE: $FAIL_TEXT"
    # A failure that repeats unchanged is reported once a day; the attempts go on as before.
    if [ "$FOREGROUND" = 1 ] || failure_report_due; then
        queue_report failure "$FAIL_CODE" "$FAIL_TEXT"
        printf '%s %s\n' "$(date +%s)" "$FAIL_CODE" > "$STATE_DIR/$NAME.failure"
    fi
    return 1
}

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 ]
}

run_worker() {  # $1 = 1 when the first attempt has just failed in the foreground
    local attempts=0 wait_index=0 wait
    exec 9> "$STATE_DIR/$NAME.lock"
    flock 9
    if [ "${1:-0}" = 1 ]; then wait_index=1; sleep "${RETRY_WAITS[0]}"; fi
    while :; do
        attempts=$((attempts + 1))
        if attempt_and_report; then break; fi
        flush_outbox
        wait=${RETRY_WAITS[$wait_index]:-${RETRY_WAITS[-1]}}
        [ "$wait_index" -lt $(( ${#RETRY_WAITS[@]} - 1 )) ] && wait_index=$((wait_index + 1))
        case "$FAIL_CODE" in ROLLED_BACK|TLS_STOPPED) wait=$STOPPED_WAIT ;; esac
        log "Attempt $attempts did not finish; the next attempt starts in $((wait / 60)) minute(s), or at once when lego saves a new certificate"
        wait_or_new_certificate "$wait"
    done
    # The next worker may install lego's next certificate while this one still sends reports.
    flock -u 9
    exec 9>&-
    # One sender is enough: a worker that finds another one sending leaves the reports to it.
    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
}

# Sleeps $1 seconds, or less when lego's certificate on disk is no longer the one just tried.
wait_or_new_certificate() {
    local left=$1 step
    while [ "$left" -gt 0 ]; do
        step=$(( left < WAKE_POLL ? left : WAKE_POLL ))
        sleep "$step"
        left=$((left - step))
        [ "$(cert_sha256 "$LEGO_PATH/certificates/$NAME.crt" 2>/dev/null)" = "${LEAF_FP:-}" ] || return 0
    done
}

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

cmd_hook() {
    require_root
    load_config || die "no settings for '$NAME' in $CONFIG_DIR; run fairssl-fortimail setup first (see FairSSL's guide)"
    open_log
    log "lego saved a certificate for $NAME; starting the deployment to FortiMail"
    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 FortiMail 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 && [ -z "$(find "$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 1
}

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

cmd_deploy() {
    require_root
    load_config || die "no settings for '$NAME' in $CONFIG_DIR; run fairssl-fortimail setup first"
    open_log
    exec 9> "$STATE_DIR/$NAME.lock"
    if ! flock -n 9; then
        say "A deployment for $NAME is already running in the background. Follow it with: sudo tail -f $LOG"
        return 0
    fi
    FOREGROUND=1
    if attempt_and_report; then
        flush_outbox || start_background_worker 0 > /dev/null
        say "Done: FortiMail serves the certificate. Renewals are installed the same way, without you."
        return 0
    fi
    flush_outbox
    exec 9>&-
    say ""
    say "The certificate is not installed yet ($FAIL_CODE). The reason is above and in the report."
    start_background_worker 1
    say "It is tried again after 1, 2, 5, 15, 30 and then every 60 minutes until it works."
    return 1
}

cmd_status() {
    local file
    require_root
    load_config || die "no settings for '$NAME' in $CONFIG_DIR"
    say "FortiMail:   $FML_USER@$FML_HOST port $FML_PORT (TLS checked on HTTPS $HTTPS_PORT and SMTP $SMTP_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" -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/fortimail renewal_id="" password=""
    local https_port=443 smtp_port=25 old_fp new_fp tool 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 ;;
            --https-port) https_port=${2:-}; shift 2 || shift ;;
            --smtp-port) smtp_port=${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_FORTIMAIL_IP ]; then
        die "--host must be FortiMail's IP address or host name (replace YOUR_FORTIMAIL_IP)"
    fi
    if ! [[ $port =~ ^[0-9]+$ && $https_port =~ ^[0-9]+$ && $smtp_port =~ ^[0-9]+$ ]]; then
        die "--port, --https-port and --smtp-port must be numbers"
    fi
    [[ $user =~ ^[A-Za-z0-9._@-]+$ ]] || die "--user must be a FortiMail 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_FORTIMAIL_WEBROOT:-/var/www/html}"
    open_log

    if [ -t 0 ]; then
        IFS= read -r -s -p "Password for $user on FortiMail $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 'FML_HOST=%s\nFML_PORT=%s\nFML_USER=%s\nHTTPS_PORT=%s\nSMTP_PORT=%s\nRENEWAL_ID=%s\nREPORT_URL=%s\nLEGO_PATH=%s\n' \
            "$host" "$port" "$user" "$https_port" "$smtp_port" "$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 FortiMail's SSH host key. Running setup again pins the key FortiMail 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 "FortiMail $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 "FortiMail's SSH host key changed from $old_fp to $new_fp; the new key is pinned."
    else
        say "FortiMail'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 FortiMail 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-fortimail $command example.com"
        shift
        "cmd_$command" "$@" ;;
    version|--version) say "fairssl-fortimail $SCRIPT_VERSION" ;;
    help|-h|--help) usage 0 ;;
    *) usage 1 ;;
esac
