#!/bin/sh
##
##   ██████▄ ▄█████▄ ▄█████▄ ██
##   ██▄▄▄██ ██   ██ ██   ██ ██
##   ██▀▀▀▀  ██   ██ ██   ██ ██
##   ██      ▀█████▀ ▀█████▀ ███████
##        ██████▄ ▄██████ ██████▄ ▄█████▄ ▐██▌ ██████▄
##        ██   ██ ██▄▄▄▄  ██▄▄▄██ ██▄▄▄██  ██  ██   ██
##        ██████  ██▀▀▀▀  ██▀▀▀▀  ██▀▀▀██  ██  ██████
##        ██  ▀██ ▀██████ ██      ██   ██ ▐██▌ ██  ▀██
##
##   Copyright © 2008-2027, Silas Mariusz <silas@qnap.com.antispam>
##                          QNAP Club Polska
##
##   www.qnaputilities.com  forum.qnap.net.pl
##
##   LICENSE: Freeware
##
##   ┌─────────┬────────────────────────────────────────────────────┐
##   │ File    │ qnap-pool-repair.sh                                │
##   ├─────────┼────────────────────────────────────────────────────┤
##   │ Package │ Pool Repair, QNAP thin pool metadata recovery      │
##   ├─────────┼────────────────────────────────────────────────────┤
##   │ Runs on │ a QNAP NAS (QTS, LVM thin pool), as admin over SSH │
##   └─────────┴────────────────────────────────────────────────────┘
##
# Interactive, menu-driven repair of QNAP thin pool metadata (pdata_tools thin_check / thin_repair / thin_restore).
# It detects the VG, the pool, the scratch LV (lv544..lv799), the RAID array under the PV (any level) and the metadata
# block size (8192/4096) on its own. The original metadata stays untouched until the repaired copy on the scratch LV
# has passed a full thin_check and, for mapping-tree damage, a read-only test mount. Session state is saved on md9, so
# a dropped connection or a reboot resumes at the right step. Operator messages are English and ASCII, except the big
# banner words (UTF-8 block characters).
#
# Paths, chosen from the thin_check result:
#   quick   space map counts only: thin_repair through the scratch LV, no LVM change, no test mount
#   full    mapping-tree errors: as above plus the temporary LVM metadata swap and an ro,noload test mount
#   legacy  thin_dump --repair + thin_restore straight to tmeta (the old SOP)
#   flag    clean metadata with needs_check set: clear the flag only
#   superblock  damaged superblock with valid backups: thin_patch --restore-superblock, then thin_check
#
# Taking the pool offline is "gentle" by default: only what belongs to the pool is unmounted and the QTS services
# are stopped only when something stays busy, so other pools keep working. The "full" mode runs the whole SOP list.
#
# --debug (or menu item 8) shows the call trace, frames every command with its number, call stack, exit code and
# duration, and writes a full shell trace to trace.log. The call trace always goes to session.log.
#
# Nothing is written to the original metadata without a verified image of it (step 3). The paths that write
# straight to the original have no way around that; the staged path has an emergency override behind
# --allow-no-backup. The saved session is read back as data, never executed.
#
# Menu item "a" (or --auto) runs the steps in a row and takes the safe defaults; it still stops for busy volumes,
# for the data check on the test mount and for the typed YES before the original is written.
#
# Before a repair the kernel log and the RAID members are checked for hardware errors (memory, disk I/O, bad
# blocks). After a repair that dropped mappings, the filesystem can be checked on the thin LV (e2fsck, read-only
# first) before QTS mounts it read-write. After the start the tool verifies that every data volume is mounted,
# looks for new kernel errors and writes report.txt. Menu 7 has the read-only viewers: command history, log pager
# and a coloured diff (also two panels side by side) of the state before and after.
#
# Shell: POSIX sh (BusyBox ash, dash, bash).
# Usage: sh qnap-pool-repair.sh [--no-screen] [--debug] [--auto] [--allow-no-backup] [--selftest]
#
# Changes in 1.7:
#   - Big banner words: a red WARNING at the start, FAILED or CRITICAL when step 4 or 5 or the automatic run fails, a green LOOKS GOOD.
#   - The banner rows are data in this file, made by gen-banners.sh from the TheDraw font "Salvation" (tdfbanner); QTS needs no tool.
#   - A failed step shows its last [FAIL] line under the word; CRITICAL is decided from the state after the step, not from the text.
#   - A finished session with every volume mounted ends with one closing line.
#   - Step 5: a mount command that ran and left no volume mounted is a [FAIL] now (it was a [WARN]); "skip" still warns.
#   - screen is started and reattached with -U: under LC_ALL=C it drew the UTF-8 block characters as garbage without it.
#   - NO_COLOR (set and not empty) turns every colour off; the banners are then one plain line, as on a dumb or narrow terminal.
#   - The start warning says what the script changes, in two lines, and waits for Enter on a terminal (not with --auto).
#   - tp_collect.sh comes over https, and a download runs only when its sha256 is the pinned one (QNAP's copy of 2020-03-27).
#   - screenfix is built in: when screen does not start, /var/run/utmp and eight terminfo files are written where missing. No download.
#   - A read-write or write-only SSD cache, or Qtier in use: step 2 and every writing step stop and point to QNAP support.
#   - A read-only SSD cache: before step 2 and before a write the script asks whether QNAP's condition is met (removed or disabled).
#   - Step 5 brings the volumes up with storage_util --sys_startup_p2 only: the volume_scan and init_lvm.sh entries left its list.
#   - Before the bring-up: /tmp/.boot_done, raid.conf and qlvm.conf are checked, QTS's storage configuration files are copied to the logs,
#     and a table of the pool's volumes is saved (bringup.expected: volume ID, LV, cachedevN, type, encryption, alert threshold, mount point).
#   - After the bring-up every volume is checked against that table, not by the exit code: one [ OK ] or [WARN] line per volume.
#   - A volume still missing: p2 once more, the rebuild with init_lvm.sh behind the typed word REBUILD (what it changed is listed after it),
#     or leave it. The automatic run stops at that question. LOOKS GOOD and the finish only when nothing is missing.
#   - A failed activation shows LVM's transaction_id of the pool next to the one in the metadata superblock.
#   - Step 5 on a pool that is already active checks the volumes, offers to mount the missing ones and starts the stopped services
#     and the snapshot manager, whatever the stage. Only the finish of the session waits for the repaired metadata.
#   - SSD cache: a cache group counts only with enabled = 1 or with a running CG<n>ssddev device; the file is /etc/config.local/ssdcache.conf.
#   - An 80x25 screen: no line of the main menu, the work directory question, the start or step 5 is over 79 columns; the menu has at most 22 lines.
#   - The red banner words (WARNING, FAILED, CRITICAL) are dark red on all six rows.
#   - Volume IDs that QTS's scan numbered anew are shown as information, not as something missing (seen on QTS 6.1.0:
#     p2 alone renumbers volume.conf; cachedevN, mount points and thresholds stayed).
#   - Messages, questions and list entries fold at spaces to the screen width: no word is broken on an 80-column screen.
#   - After the rebuild every setting init_lvm.sh changed in raid.conf, qlvm.conf, ssdcache.conf and qdrbd.conf is listed
#     (rebuild.diff in the logs); seen on QTS 6.1.0: [RAID_1] readAhead 4096 -> 0, besides the alert thresholds.
#   - A work directory whose disk is gone no longer makes every log line print "No such file or directory" (the
#     redirections were in the wrong order for that); seen on QTS 6.1.0 with the work disk unmounted mid-session.
#   - Step 5 lists the volumes' mount points; the mounts of apps and containers on them are only counted.
#   - At the start every command the script uses is looked up (need_list, kept in step with the script by
#     check-commands.py): a missing required one stops before anything is changed, missing optional ones are named.
#   - A self-test, read-only: known answers from awk, sed, grep, diff, cmp, sort, date, dd, gzip, sha256sum, and the
#     storage tools asked for their version. Offered once for a new session, in Tools p, and as --selftest.
#   - While the checks run, a spinner ("Checking dependencies...", "Testing tools..."): ASCII frames, braille ones
#     only in the script's own screen session from a UTF-8 locale; none when the output is not a terminal.
#   - Every command that changes the storage stack or the services is recorded with its exit code and its undo
#     (changes.log); under a FAILED or CRITICAL banner the script shows the last failed change, what was changed
#     before it and the way back; report.txt lists them all under "Commands that changed the system".
#
# ##################################################################################################
# ##  TODO: SSD cache (read-write / write-only) and Qtier - not built, not tested                 ##
# ##################################################################################################
# What the script does today:
#   - A read-write or write-only SSD cache (ssdcache.conf mode 1 or 4, WRITE_BACK in dmsetup status), or Qtier
#     with data in two or more tiers: step 2 and every writing step stop and point to QNAP support. No
#     question, no override. The diagnosis still runs and reports it.
#   - A cache group counts only with enabled = 1 in its [CG_n] section, or with a running CG<n>ssddev device.
#   - A read-only SSD cache (mode 2, WRITE_THROUGH_ENHANCED): it asks whether the cache is removed, or disabled
#     with this pool's volumes deselected from it (the condition of QNAP's fcorig SOP). Default: no.
#   - The cache type detection has NEVER run on a NAS with an SSD cache. It follows QNAP's slides only
#     (docs/SSD cache.pptx): the file, the section and the key, the device name CG0ssddev, the status words.
#   - Qtier is seen only in a superblock thin_dump -b can read. Step 1 tries it on the live pool too; where that
#     read is refused, the stop comes after step 2, at the diagnosis with the pool offline and at step 4.
# What the admin does and checks by hand before a metadata repair of such a pool:
#   - QTS, Storage & Snapshots, Cache Acceleration: switch a read-write cache to read-only, or remove it,
#     so that it is flushed.
#   - dmsetup status CG0ssddev                         shows WRITE_THROUGH_ENHANCED, or no CG device is left
#   - getcfg CG_0 enabled -f /etc/config.local/ssdcache.conf    1 = the cache group is in use
#   - getcfg CG_0 mode -f /etc/config.local/ssdcache.conf       2 = read-only (1 = read-write, 4 = write-only)
#   - Qtier: QNAP support. The pool metadata carries the tier maps; thin_dump -b shows tierN_data_blocks.
# Still to build and to test, once a unit with an SSD cache is available:
#   - the detection on real output (ssdcache.conf in /etc/config.local, dmsetup status)
#   - the cache of a single pool vs all pools (today a cache group anywhere on the NAS counts for this pool)
#   - a flush or a detach with the pool offline, if QNAP documents one (no document here shows one)
#   - the repair with a read-only cache in place
#   - init_lvm.sh and ssdcache.conf (init_lvm.sh moves the file aside and rebuilds it)
#   - Qtier pools
# ##################################################################################################
#
# Changes in 1.6 (from the first runs on QTS 6.1.0):
#   - LVM no longer prints "File descriptor N leaked ..." before every answer: clean logs, a clean compare view.
#   - A repeated backup keeps the previous image until the new one is verified; after that only the new one is left.
#   - The gzip backup shows a bar with percent and time left, counted from the bytes read from the device.
#   - The filesystem check tells a damaged ext4 superblock from an encrypted volume; e2fsck's exit code is read as flags.
#   - Commands that can leave a daemon behind (services, iSCSI, init_lvm, storage_util) write to /tmp: the work disk unmounts.
#   - report.txt quotes the thin_check that set the diagnosis, also after a restart (its name is kept in the session state).
#   - Quick path: the data note no longer points at a test mount this path does not have; it offers the full path instead.
#   - The test mount list starts with the volumes thin_check named and marks them; the automatic run moves on with [o].
#   - A damaged primary superblock: the repair looks through the standard backup places for one that opens, not only 32768.
#   - Once QTS has built cachedevN on a volume (not mounted), the filesystem repair runs on cachedevN: the LV is "in use".
#   - Step 5 on a running pool looks at the volumes again and offers to mount once more while one is missing.
#   - Disk I/O errors are counted for the devices under this pool only; lines about other disks are shown, they do not gate.
#   - init_lvm.sh rebuilds QTS's volume configuration: its files are copied to the logs first, a note tells what changed.
#   - report.txt after a restart of the script: the hardware check runs for the report instead of "not checked".
#   - report.txt lists the volumes as they are when the session is finished, not as they were after the first step 5.
#   - A damaged superblock with valid backups: step 4 offers the restore from the newest one (thin_patch) before the full path.
#   - A superblock restore that ends with a clean thin_check finishes the repair: step 5 no longer asks "anyway?".
#   - A failed XML dump no longer leaves an empty thin_dump.xml in the work directory.
#   - The hardware check prints its "Details:" line once.
#   - Without a work directory the logs go to md9 (next to the session state) when it has room, not to /tmp: a reboot keeps them.
#   - Step 5: the third choice runs storage_util --volume_scan; it ran sys_startup_p2, because that name is in the line's text.
#   - The hardware check counts real machine check reports only, not "mce: Machine check injector initialized" of every boot.
#   - The [b] reboot with the pool flagged offline: step 5 rebuilds the apps' rc links (qpkg --set-rc-seq) and starts the services.
#   - A missing work directory no longer prints a shell error each time the session state is saved.
#   - The logs go back to the work directory when its disk returns while the script runs.
#   - The temporary LVM state carries the skip-activation flag (a reboot leaves the pool down); a pool run on the copy is named.

VERSION="1.7"
SESSION="qnap-pool-repair"

# the caller's locale, kept before LC_ALL=C: the spinner draws braille frames only for a UTF-8 terminal
QPR_LOC0=${QPR_LOC0:-${LC_ALL:-${LC_CTYPE:-${LANG:-}}}}
export QPR_LOC0
case "$QPR_LOC0" in *[Uu][Tt][Ff]-8* | *[Uu][Tt][Ff]8*) QPR_UTF8=1 ;; *) QPR_UTF8="" ;; esac
LC_ALL=C
export LC_ALL
# every place QTS keeps the tools this script runs (need_list): LVM, dmsetup, mdadm, pdata_tools, storage_util in
# /sbin, BusyBox and e2fsck in /bin, screen and lsof in /usr/sbin; then what the caller had
PATH="/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PATH"
export PATH
# QTS: every LVM command starts with "File descriptor N (/dev/pts/M) leaked on ... invocation" without this
LVM_SUPPRESS_FD_WARNINGS=1
export LVM_SUPPRESS_FD_WARNINGS

# Our own files (logs, state, work directory) are for the admin only. Everything the script runs gets the
# umask it was started with back: services started from here must not inherit a restrictive one.
UMASK0="${QPR_UMASK0:-$(umask)}"
QPR_UMASK0=$UMASK0
export QPR_UMASK0
umask 077

# bash (QTS runs it as sh) keeps COLUMNS and LINES current with this on; other shells have no such option,
# and QTS has no stty to ask the terminal with
# shellcheck disable=SC3044
if [ -n "${BASH_VERSION:-}" ]; then shopt -s checkwinsize 2>/dev/null; fi

# QTS runs BusyBox 1.24: a bare printf can be missing outside an interactive shell, "busybox printf" works
if ! command -v printf >/dev/null 2>&1; then
  printf() { busybox printf "$@"; }
fi

# ==================================================================================================
#  Settings. The QPR_* variables exist only for the tests against mock tools.
# ==================================================================================================
DEVMAP="${QPR_DEVMAP:-/dev/mapper}"                    # device-mapper nodes
F_MDSTAT="${QPR_MDSTAT:-/proc/mdstat}"                 # RAID state
F_MOUNTS="${QPR_MOUNTS:-/proc/mounts}"                 # what is mounted
F_MEMINFO="${QPR_MEMINFO:-/proc/meminfo}"              # memory and swap
F_DRBD="${QPR_DRBD:-/proc/drbd}"                       # DRBD roles
F_SWAPS="${QPR_SWAPS:-/proc/swaps}"                    # active swap areas
PERSIST="${QPR_PERSIST:-/mnt/HDA_ROOT/.pool_recovery}" # session state that survives a reboot (md9)
TRYMNT="${QPR_TRYMNT:-/mnt/tryMount}"                  # mount point of the read-only test
TMPD="${QPR_TMP:-/tmp}"                                # run copy, lock, first log lines; all logs when md9 has no room
EXTBASE="${QPR_EXTBASE:-/share/external}"              # where QTS mounts external disks
INITD="${QPR_INITD:-/etc/init.d}"                      # QTS init scripts
DAEMON_MGR="${QPR_DAEMON_MGR:-/sbin/daemon_mgr}"       # QTS daemon manager (lvmetad)
QPKG="${QPR_QPKG:-/sbin/qpkg}"                         # QTS package tool (start links of the apps)
CONFD="${QPR_CONFD:-/etc/config}"                      # QTS configuration
POLL="${QPR_POLL:-1}"                                  # seconds between two looks at a running long command
CONFL="${QPR_CONFL:-/etc/config.local}"                # QTS's storage configuration: raid.conf, qlvm.conf, ssdcache.conf
F_VOLCONF="${QPR_VOLCONF:-/etc/volume.conf}"           # QTS's volume table; every storage scan writes it anew
F_LVMRT="${QPR_LVMRT:-/tmp/lvm_runtime_info}"          # QTS's run-time state of the pools
F_BOOTDONE="${QPR_BOOTDONE:-/tmp/.boot_done}"          # there once QTS has finished booting
TERMINFO_DIR="${QPR_TERMINFO:-/usr/share/terminfo}"    # terminal descriptions; screen_files adds the missing ones
F_UTMP="${QPR_UTMP:-/var/run/utmp}"                    # screen does not start without this file
URL_TPCOLLECT="https://download.qnap.com/Storage/tsd/utility/tp_collect.sh"
URL_PDATA_ALT="https://download.qnap.com/Storage/tsd/utility"
# A downloaded tp_collect.sh runs only with this sha256: QNAP's copy of 2020-03-27, 6728 bytes
TPCOLLECT_SHA256="${QPR_TPCOLLECT_SHA256:-9e2693389917016dd05f07cdcc8268ab01c422e62d34452bbd1a165bbfb4e1ec}"
# Without a work directory the logs go to $PERSIST/logs/<session id> on md9: a reboot keeps them there, /tmp loses
# them. md9 is about 500 MB with few inodes (8K on some models) and QTS needs it to boot and to install apps, so it
# is used only above this floor, checked at every start. The output cap that protects the 64 MB /tmp stays on:
# it limits the output of one command, not of a session, and session.log grows with every command.
PLOG_MIN_MB=32       # free space on md9 under which the logs stay in /tmp, MiB
PLOG_MIN_INODES=2000 # the same for free inodes
PLOG_KEEP=5          # session log folders kept on md9; older ones are removed at the start

# ==================================================================================================
#  Session state: saved to $PERSIST/state after every step, read back on the next start
# ==================================================================================================
STATE_VARS="VG POOL META TMPLV PDATA WORKDIR STAGE CLASS RPATH SERVICES_STOPPED QSNAP_STOPPED BACKUP_FILE BACKUP_KIND XML_OK NOBACKUP DATA_ACK AFFECTED DIAG_TC FSCK COPY_LIVE TIERS_USED STARTED"
VG=""               # volume group of the pool, e.g. vg1
POOL=""             # thin pool LV, e.g. tp1
META=""             # its metadata LV, e.g. tp1_tmeta
TMPLV=""            # scratch LV that takes the repaired copy, e.g. lv544
PDATA=""            # pdata_tools binary matching the metadata block size
WORKDIR=""          # work directory: logs, metadata image, LVM configuration copies
STAGE="new"         # where the session stands, see stage_desc
CLASS=""            # diagnosis: CLEAN SPACEMAP MAPPING SUPERBLOCK UNKNOWN
RPATH=""            # repair path: quick full legacy rebuild flag superblock
SERVICES_STOPPED="" # 1 = this script stopped the full QTS service list, or flagged the pool offline for a reboot ([b])
QSNAP_STOPPED=""    # 1 = this script stopped the snapshot manager
BACKUP_FILE=""      # image of the original metadata
BACKUP_KIND=""      # raw | gz
XML_OK=""           # 1 = thin_dump.xml in the work directory is complete
NOBACKUP=""         # 1 = the operator chose to go on without a backup (--allow-no-backup only)
DATA_ACK=""         # yes | no: is there a separate backup of the data (asked once, recorded)
AFFECTED=""         # data volumes thin_check named as damaged, e.g. "lv1 lv4"
DIAG_TC=""          # thin_check log that set the diagnosis: its file name in the log directory
FSCK=""             # filesystem check before the first read-write mount: done | skip | "" (not decided)
COPY_LIVE=""        # 1 = the pool ran read-write on the working copy (a reboot in the temporary state), see copy_live
TIERS_USED=""       # tiers of the pool that hold data (2 or more = Qtier in use); saved, so that a restart keeps the stop
STARTED=""          # when the session began

# ==================================================================================================
#  Working variables (not saved)
# ==================================================================================================
CWD=""                                     # directory the script was started from; helper files are looked up there
NO_SCREEN=""                               # --no-screen
IN_SCREEN=""                               # set in the copy that runs inside screen
RUNCOPY=""                                 # the copy in /tmp that actually runs
DEBUG="${QPR_DEBUG:-}"                     # --debug: call trace on the screen, framed commands, shell trace file
AUTO=""                                    # 1 = automatic run: safe defaults are taken without asking
AUTO_START=""                              # --auto: start the automatic run right after the detection
SELFTEST=""                                # --selftest: the self-test only, then exit
ALLOW_NO_BACKUP="${QPR_ALLOW_NO_BACKUP:-}" # --allow-no-backup: emergency override, staged path only
LOGDIR=""                                  # directory of the logs
LOG=""                                     # session.log
CMDLOG=""                                  # commands.log
RCF=""                                     # file that carries the exit code of a background command
RC=0                                       # exit code of the last run/run_long command
STACK=""                                   # call stack of the traced functions, "a > b > c"
IND=""                                     # indentation of the call trace
CMD_SEQ=0                                  # running number of the commands
TRACE_ON=""                                # 1 = set -x is writing to trace.log
OUT_CAP=""                                 # line cap for command output while the logs sit on md9 or in /tmp
PLOG_WHY=""                                # persist_room: why md9 does not take the logs
TERM_REQ=""                                # 1 = SIGTERM arrived, stop after the current step
LAST_ERR=""                                # text of the last err line; cleared when a step starts, see fail_banner
END_WAIT=""                                # 1 = an end banner is on the screen: wait for Enter before the menu
MOUNT_RAN=""                               # 1 = startup_mount ran a QTS mount command (not "skip", not cancelled)
BRINGUP_TAG=""                             # name ending of the copies bringup_save made before the last bring-up
BRINGUP_MISS=""                            # bringup_check: what is missing or not as saved, "; " between the items
BRINGUP_CHG=""                             # bringup_check after a rebuild: what differs from the saved table, in lines
BRINGUP_IDS=""                             # bringup_check: volume IDs QTS numbered anew (information, not a fault)
LOCKDIR=""                                 # lock directory of this instance
MODEL=""                                   # NAS model
FW=""                                      # Version from uLinux.conf (not always the real firmware)
KVER=""                                    # kernel release
HOST=""                                    # host name
LVTAB=""                                   # LVs of the VG: name|attributes|size MiB|pool
VGDM=""                                    # VG name as device-mapper writes it
METADEV=""                                 # device node of the metadata LV
TMPDEV=""                                  # device node of the scratch LV
META_MB=0                                  # size of the metadata LV in MiB
RAID_SUM=""                                # one-line state of the RAID arrays under the VG
RAID_STATE="unknown"                       # ok | degraded | syncing | inactive | unknown
PV_MISSING=""                              # PVs of the VG that LVM flags as missing
LVM_PARTIAL=""                             # 1 = partial LVs in the VG
LVM_CACHE=""                               # 1 = SSD cache layer (cache_client / fcorig) in the VG
VG_SKIP=""                                 # 1 = skip-activation flag on the VG (lvchange -ky)
CACHE_MODE="none"                          # SSD cache type, see cache_mode: none | ro | rw | unknown
CACHE_SRC=""                               # the line that named it
CACHE_ACK=""                               # 1 = the operator confirmed the SSD cache condition, or accepted the cache layer
SF_WROTE=""                                # screen_files: what it wrote
SF_FAIL=""                                 # screen_files: what it could not write
TC_FILE=""                                 # output file of the last thin_check
TC_RC=0                                    # its exit code
TC_CLASS=""                                # its classification
TC_INFO=""                                 # its error line counts per section
ORIG_TC=""                                 # thin_check output of the original metadata, for the backup comparison
SB_LINE=""                                 # superblock line of thin_dump -b
SB_FLAGS=""                                # its flags value; odd = needs_check
SB_TRANS=""                                # its transaction id
ST_UPPER=""                                # dm devices above the LVs (cachedevN, ce_cachedevN), top first
ST_VGDEVS=""                               # dm devices of the VG
ST_MPS=""                                  # mount points of that whole stack, deepest first
PICK=""                                    # line chosen in pick
PICK_LIST=""                               # lines offered by pick
ANS=""                                     # last answer typed by the operator
RL_SAVE=""                                 # run_long: extra copy of the output
RL_WATCH=""                                # run_long: file whose size is shown as progress
RL_TOTAL=""                                # run_long: expected size in MiB
RL_READ=""                                 # run_long: file with the PID whose bytes read are the progress
RL_CRIT=""                                 # run_long: 1 = metadata write, ignore SIGTERM, never pipe the output
RL_DAEMON=""                               # run_long: 1 = the command can leave a daemon behind, see run_daemon
TEST_RESULT=""                             # outcome of the test mount: ok | bad | skip
HEALTH_DONE=""                             # 1 = health_check ran in this run of the script
HEALTH_MEM=""                              # kernel log: lines about hardware memory errors
HEALTH_IO=""                               # kernel log: lines about disk I/O errors on the devices under the pool
HEALTH_OOM=""                              # kernel log: out-of-memory lines
HEALTH_BB=""                               # RAID members with recorded bad blocks
HEALTH_DRBD=""                             # DRBD device that is not Primary
HW_ACK=""                                  # 1 = the operator accepted memory errors
IO_ACK=""                                  # 1 = the operator accepted disk errors
INITLVM_TAG=""                             # name ending of the configuration copies made before init_lvm.sh
E2FSCK=""                                  # e2fsck_64 or e2fsck
SB_BLOCK=""                                # sb_find: the backup superblock that opens ("" = the primary does)
VERIFY_MISS=""                             # data volumes not mounted after the start
REPORT_FILE=""                             # where make_report wrote the report
COLS=80                                    # terminal width used by the viewers
ROWS=24                                    # terminal height used by the viewers

# ==================================================================================================
#  User interface and logging
# ==================================================================================================
if [ -t 1 ]; then IS_TTY=1; else IS_TTY=""; fi
if [ -n "$IS_TTY" ] && [ -z "${NO_COLOR:-}" ]; then # NO_COLOR set and not empty: no colours at all
  C_R=$(printf '\033[1;31m')
  C_G=$(printf '\033[1;32m')
  C_Y=$(printf '\033[1;33m')
  C_B=$(printf '\033[1;36m')
  C_D=$(printf '\033[0;36m')
  C_RD=$(printf '\033[0;31m') # the darker red and green of the lower banner rows
  C_GD=$(printf '\033[0;32m')
  C_0=$(printf '\033[0m')
else
  C_R=""
  C_G=""
  C_Y=""
  C_B=""
  C_D=""
  C_RD=""
  C_GD=""
  C_0=""
fi

ts() { date '+%Y-%m-%d %H:%M:%S'; }
logf() { if [ -n "$LOG" ]; then printf '[%s] %s\n' "$(ts)" "$*" 2>/dev/null >>"$LOG"; fi; }
# fold_out <width of what is already on the line> <text>: the text folded at spaces to the screen width (COLS - 1),
# so that an 80x25 terminal never breaks a word; continuation lines start under the text. A line that fits is
# printed as it is; a word longer than the line (a path) stays whole. The logs always get the line unfolded.
fold_out() {
  printf '%s\n' "$2" | awk -v w="$((${COLS:-80} - 1))" -v p="$1" '
    function pad(k, s) { s = ""; while (k-- > 0) s = s " "; return s }
    {
      pre = (NR == 1 ? "" : pad(p))
      if (length($0) + p <= w) { print pre $0; next }
      match($0, /^ */); lead = RLENGTH; t = substr($0, lead + 1)
      avail = w - p - lead; if (avail < 20) avail = 20
      n = split(t, a, / +/); line = ""
      for (i = 1; i <= n; i++) {
        if (line == "") line = a[i]
        else if (length(line) + 1 + length(a[i]) <= avail) line = line " " a[i]
        else { print pre pad(lead) line; pre = pad(p); line = a[i] }
      }
      print pre pad(lead) line
    }'
}

say() {
  fold_out 0 "$*"
  logf "$*"
}
ok() {
  printf '%s[ OK ]%s ' "$C_G" "$C_0"
  fold_out 7 "$*"
  logf "OK: $*"
}
warn() {
  printf '%s[WARN]%s ' "$C_Y" "$C_0"
  fold_out 7 "$*"
  logf "WARN: $*"
}
err() {
  printf '%s[FAIL]%s ' "$C_R" "$C_0"
  fold_out 7 "$*"
  logf "FAIL: $* (in: ${STACK:-main})"
  LAST_ERR="$*"
  if [ -n "$DEBUG" ]; then printf '%s       in: %s%s\n' "$C_D" "${STACK:-main}" "$C_0"; fi
}
note() { say "       $*"; } # continuation line under ok/warn/err
hdr() {
  printf '\n%s=== %s ===%s\n' "$C_B" "$*" "$C_0"
  logf "=== $* ==="
}

# banner KIND [reason]: KIND = warning | failed | critical | good. The word in big letters (banner_rows, at the
# end of this section) when the terminal can show them: colours on, not a dumb terminal, wide enough. Everywhere
# else one plain line. The reason comes under it. session.log gets one line, never the rows.
banner() {
  local __w __c1 __c2 __n=0 __row
  __c1=$C_RD # the red words are dark red on all six rows
  __c2=$C_RD
  case "$1" in
    warning) __w=WARNING ;;
    failed) __w=FAILED ;;
    critical) __w=CRITICAL ;;
    good)
      __w="LOOKS GOOD"
      __c1=$C_G
      __c2=$C_GD
      ;;
    *) return 0 ;;
  esac
  logf "BANNER: $__w${2:+ - $2}"
  term_size
  if [ -n "$IS_TTY" ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ] &&
    [ "$COLS" -ge $(($(banner_width "$__w") + 2)) ]; then
    printf '\n'
    banner_rows "$__w" | while IFS= read -r __row; do # LOOKS GOOD: the top two rows bright, the rest dark
      __n=$((__n + 1))
      if [ "$__n" -le 2 ]; then __row="$__c1$__row"; else __row="$__c2$__row"; fi
      printf '  %s%s\n' "$__row" "$C_0"
    done
    printf '\n'
  else
    printf '%s*** %s ***%s\n' "$__c1" "$__w" "$C_0"
  fi
  if [ -n "${2:-}" ]; then printf '%s\n' "$2"; fi
}

enter_wait() { # enter_wait "prompt": a pause on a terminal, so that a banner is read before the screen moves on
  if [ -z "$IS_TTY" ] || [ ! -t 0 ] || [ -n "$QPR_TEST" ]; then return 0; fi
  rdq "$1"
}

fmt_dur() { printf '%02d:%02d:%02d' $(($1 / 3600)) $(($1 % 3600 / 60)) $(($1 % 60)); }
fit() { # fit MAX TEXT: TEXT as it is, or with ".." in place of its middle when it is longer than MAX columns
  if [ "${#2}" -le "$1" ]; then
    printf '%s' "$2"
    return 0
  fi
  printf '%s\n' "$2" | awk -v n="$1" '{ t = int(n / 3); printf "%s..%s", substr($0, 1, n - 2 - t), substr($0, length($0) - t + 1) }'
}
fsize() { ls -ln "$1" 2>/dev/null | awk '{print $5; exit}'; }
free_mb() { df -k "$1" 2>/dev/null | tail -n 1 | awk '{printf "%d", $(NF-2)/1024}'; }
is_blk() { [ -b "$1" ] || { [ -n "$QPR_TEST" ] && [ -e "$1" ]; }; }
have() { command -v "$1" >/dev/null 2>&1; }

# rd "question" -> the answer lands in ANS; closed input stops the script safely
rd() {
  printf '%s' "$(fold_out 0 "$1")" # the answer goes on the last line of the question
  if ! IFS= read -r ANS; then
    printf '\n'
    logf "Input closed (EOF / dropped session) - stopping between steps."
    safe_exit 3
  fi
  logf "? $1 -> $ANS"
}

auto_say() {
  printf '%s  [auto] ' "$C_D"
  fold_out 9 "$*$C_0"
  logf "[auto] $*"
}

ask_yn() { # ask_yn "question" [y|n]  (the default answer; the automatic run takes it without asking)
  if [ -n "$AUTO" ]; then
    auto_say "$1 -> ${2:-n}"
    [ "${2:-n}" = y ]
    return $?
  fi
  while :; do
    if [ "${2:-n}" = y ]; then rd "$1 [Y/n]: "; else rd "$1 [y/N]: "; fi
    case "$ANS" in
      y | Y | yes | YES | t | T) return 0 ;;
      n | N | no | NO) return 1 ;;
      '') if [ "${2:-n}" = y ]; then return 0; else return 1; fi ;;
    esac
  done
}

ask_file() { # ask_file "question" [default] -> an existing, non-empty file in ANS; 1 otherwise
  rd "$1${2:+ [$2]}: "
  if [ -z "$ANS" ]; then ANS=$2; fi
  if [ -z "$ANS" ] || [ ! -s "$ANS" ]; then
    err "No such file: ${ANS:-(none given)}"
    return 1
  fi
  return 0
}

ask_word() { # ask_word WORD  - confirmation of an irreversible operation
  rd "Type $1 to confirm (anything else cancels): "
  [ "$ANS" = "$1" ]
}

pick() { # pick "question"; the list is in PICK_LIST (lines); result in PICK; 1 = cancelled
  local __n __i __l
  __n=$(printf '%s\n' "$PICK_LIST" | grep -c .)
  printf '%s\n' "$PICK_LIST" | grep . | {
    __i=0
    while IFS= read -r __l; do
      __i=$((__i + 1))
      printf '  %d) ' "$__i"
      fold_out 5 "$__l"
    done
  }
  printf '  0) cancel\n'
  if [ -n "$AUTO" ]; then # the lists are ordered with the recommended entry first
    PICK=$(printf '%s\n' "$PICK_LIST" | grep . | sed -n 1p)
    auto_say "$1 -> 1) ${PICK%%  *}"
    return 0
  fi
  while :; do
    rd "$1 [0-$__n]: "
    case "$ANS" in
      0) return 1 ;;
      '' | *[!0-9]*) continue ;;
    esac
    if [ "$ANS" -ge 1 ] && [ "$ANS" -le "$__n" ]; then
      PICK=$(printf '%s\n' "$PICK_LIST" | grep . | sed -n "${ANS}p")
      return 0
    fi
  done
}

# >>> banners: generated by gen-banners.sh from the TheDraw font "Salvation" (tdfbanner); do not edit
banner_width() { # banner_width WORD: its width in columns
  case "$1" in
    WARNING) echo 56 ;;
    FAILED) echo 41 ;;
    CRITICAL) echo 53 ;;
    "LOOKS GOOD") echo 74 ;;
  esac
}

banner_rows() { # banner_rows WORD: its rows, top first
  case "$1" in
    WARNING)
      printf '%s\n' \
        '▄▄▄    ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄  ▄▄▄  ▄▄▄ ▄▄▄ ▄▄▄  ▄▄▄  ▄▄▄▄▄' \
        '███    ███ ███ ███ ███ ███ ████▄███ ███ ████▄███ ███ ███' \
        '▓▓▓    ▓▓▓ ▓▓▓▀▓▓▓ ▓▓▓ █▓█ ▓▓▓ ▀▓▓▓ ▓▓▓ ▓▓▓ ▀▓▓▓ ▓▓▓ ▀▀▀' \
        '▒▒▒ ▄▌ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒▀▀▀▄ ▒▒▒  ▒▒▒ ▒▒▒ ▒▒▒  ▒▒▒ ▒▒▒▀▒▒▒' \
        '░░░█▀▀█░░░ ░░░ ░░░ ░░░ █░█ ░░░  ░░░ ░░░ ░░░  ░░░ ░░░ ░░░' \
        '▀▀▀    ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀  ▀▀▀ ▀▀▀ ▀▀▀  ▀▀▀  ▀▀▀▀▀▀'
      ;;
    FAILED)
      printf '%s\n' \
        '▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄   ▄▄▄▄▄▄▄ ▄▄▄▄▄▄' \
        '███ ███ ███ ███ ███ ███   ███ ███ ███ ███' \
        '▓▓▓▄▀▀▀ ▓▓▓▀▓▓▓ ▓▓▓ ▓▓▓   ▓▓▓▄▀▀▀ ▓▓▓ ▓▓▓' \
        '▒▒▒     ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒   ▒▒▒ ▄▄▄ ▒▒▒ ▒▒▒' \
        '░░░     ░░░ ░░░ ░░░ ░░░   ░░░ ░░░ ░░░ ░░░' \
        '▀▀▀     ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀▀▀ ▀▀▀▀▀▀▀ ▀▀▀▀▀▀'
      ;;
    CRITICAL)
      printf '%s\n' \
        '▄▄▄▄▄▄▄ ▄▄▄▄▄▄  ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄' \
        '███ ███ ███ ███ ███   ███   ███ ███ ███ ███ ███ ███' \
        '▓▓▓ ▀▀▀ ▓▓▓ █▓█ ▓▓▓   ▓▓▓   ▓▓▓ ▓▓▓ ▀▀▀ ▓▓▓▀▓▓▓ ▓▓▓' \
        '▒▒▒ ▄▄▄ ▒▒▒▀▀▀▄ ▒▒▒   ▒▒▒   ▒▒▒ ▒▒▒ ▄▄▄ ▒▒▒ ▒▒▒ ▒▒▒' \
        '░░░ ░░░ ░░░ █░█ ░░░   ░░░   ░░░ ░░░ ░░░ ░░░ ░░░ ░░░' \
        '▀▀▀▀▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀   ▀▀▀   ▀▀▀ ▀▀▀▀▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀▀▀'
      ;;
    "LOOKS GOOD")
      printf '%s\n' \
        '▄▄▄   ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄       ▄▄▄▄▄  ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄' \
        '███   ███ ███ ███ ███ ███ ███ ███▄▄▄▄      ███ ███ ███ ███ ███ ███ ███ ███' \
        '▓▓▓   ▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓▀▓▓▄ ▀▀▀▀▓▓▓      ▓▓▓ ▀▀▀ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓' \
        '▒▒▒   ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒      ▒▒▒▀▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒ ▒▒▒' \
        '░░░   ░░░ ░░░ ░░░ ░░░ ░░░ ░░░ ░░░ ░░░      ░░░ ░░░ ░░░ ░░░ ░░░ ░░░ ░░░ ░░░' \
        '▀▀▀▀▀ ▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀▀▀▀▀       ▀▀▀▀▀▀ ▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀ ▀▀▀▀▀▀'
      ;;
  esac
}
# <<< banners

# ==================================================================================================
#  The commands this script needs, a self-test of them, and the record of what it changed
# ==================================================================================================
# need_list: every external command the script runs. r = it cannot repair without it, o = optional (what is lost
# without it), p = only asked whether it is there (never reported); R and O = r and o for a command it runs by a variable ($PDATA, $E2FSCK, $INITD/..., $DAEMON_MGR,
# $QPKG, the base64 decoder). check-commands.py on the build machine fails when this list and the script part.
need_list() {
  printf '%s\n' \
    'r awk reads the output of every command' \
    'r cat shows the logs and copies the state' \
    'r chmod keeps the logs and the state private' \
    'r cp copies the configuration and the logs' \
    'r cut reads fields of command output' \
    'r date times the commands and names the logs' \
    'r dd makes and checks the metadata image' \
    'r df finds a work directory with room' \
    'r dirname finds where the script was started' \
    'r dmesg reads the kernel log for hardware errors' \
    'r dmsetup removes and lists the device-mapper devices' \
    'r grep reads the output of every command' \
    'r head shortens long command output' \
    'r id checks that the script runs as admin' \
    'r lvchange activates and flags the logical volumes' \
    'r ls lists files and device sizes' \
    'r lvs lists the pool, its volumes and their state' \
    'r mkdir makes the log and work directories' \
    'r mount mounts the copy for the read-only test' \
    'r mv puts finished files in place' \
    'r pvs finds a physical volume in missing mode' \
    'r rm removes temporary files' \
    'r sed reads and edits text and LVM configurations' \
    'r sh runs the script copy and QNAP helpers' \
    'r sleep waits for long commands' \
    'r sort orders lists' \
    'r storage_util lets QTS build cachedevN and mount the volumes (step 5)' \
    'r tail shortens long command output' \
    'r touch marks the screen session as started' \
    'r tr cleans command output' \
    'r umount unmounts the volumes of the pool (step 2)' \
    'r vgcfgbackup saves the LVM configuration' \
    'r vgcfgrestore swaps the pool to the working copy and back' \
    'r vgchange activates and deactivates the volume group' \
    'r wc counts lines and bytes' \
    'o blockdev size of a device: the image check uses ls instead' \
    'o busybox printf when the shell has none' \
    'o cmp quick compare of two files: diff is used instead' \
    'o cryptsetup encrypted volumes: they are not told from damaged ones' \
    'o diff the before/after view of the logs menu' \
    'o dumpe2fs the search for a backup ext4 superblock' \
    'o dumpe2fs_64 the search for a backup ext4 superblock' \
    'o e2fsck the filesystem check before the first mount' \
    'o e2fsck_64 the filesystem check before the first mount' \
    'o getcfg the firmware version in the logs' \
    'o getsysinfo the NAS model in the logs' \
    'o gzip the packed metadata image (a raw image is made instead)' \
    'o hexdump the metadata block size (od is used instead)' \
    'o hostname the host name in the logs' \
    'o less the log viewer uses its own pager' \
    'o lsof the list of programs that keep a volume busy' \
    'o md5sum checksums (sha256sum is used first)' \
    'o mdadm bad blocks recorded on the RAID members' \
    'o od the metadata block size (hexdump is used instead)' \
    'o pdata_tools the thin pool tools under that name' \
    'o pvscan a rescan of the physical volumes' \
    'o rmdir removes empty log directories' \
    'o screen a dropped SSH session stops the work between steps' \
    'o sha256sum checksums of the helpers and images (md5sum is used instead)' \
    'o swapoff a swap file on the pool keeps it busy in step 2' \
    'o sync flushes before a reboot' \
    'o tar the log package for QNAP' \
    'o tput the terminal size (80x24 is assumed)' \
    'o uname the kernel version in the logs' \
    'o vgextend Tools i, a physical volume in missing mode' \
    'o wget the download of tp_collect.sh' \
    'p zpool is there only on QuTS hero (ZFS): its absence is the normal case here' \
    'O pdata_tools_8192 thin_check and thin_repair for 8192-byte metadata blocks' \
    'O pdata_tools_4096 thin_check and thin_repair for 4096-byte metadata blocks' \
    'O openssl decodes the built-in terminfo files (base64 is used instead)' \
    'O base64 decodes the built-in terminfo files (openssl is used first)' \
    'O daemon_mgr starts lvmetad again after step 2' \
    'O qpkg makes the start links of the apps after a reboot' \
    'O services.sh stops and starts the QTS services' \
    'O qsnapman.sh stops and starts the snapshot manager' \
    'O qulog.sh stops the system log (full stop of step 2)' \
    'O iscsitrgt.sh restarts the iSCSI service after step 5' \
    'O init_lvm.sh the rebuild of QTS'"'"'s storage configuration (step 5, on request)'
}

need_have() { # need_have <command>: is it there; the commands run by variable are looked up where the script runs them
  case "$1" in
    *.sh) [ -x "$INITD/$1" ] ;;
    daemon_mgr) [ -x "$DAEMON_MGR" ] ;;
    qpkg) [ -x "$QPKG" ] ;;
    *) have "$1" ;;
  esac
}

# The spinner: one status line rewritten in place while a check runs. ASCII frames by default, so that PuTTY and
# any terminal draw them; braille frames only inside this script's own screen -U session started from a UTF-8
# locale. Nothing when the output is not a terminal, with NO_COLOR, or with TERM=dumb: then the results are lines.
SPIN_ON=""
SPIN_N=0
SPIN_LABEL=""
spin_start() { # spin_start "label"
  SPIN_LABEL=$1
  SPIN_N=0
  SPIN_ON=""
  if [ -n "$IS_TTY" ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ] && [ -z "$QPR_TEST" ]; then
    SPIN_ON=1
    spin_tick
  fi
}
spin_tick() {
  local __f
  if [ -z "$SPIN_ON" ]; then return 0; fi
  SPIN_N=$((SPIN_N + 1))
  if [ -n "$IN_SCREEN" ] && [ -n "$QPR_UTF8" ]; then
    __f=$(printf '%s\n' "⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏" | awk -v n="$SPIN_N" '{print $((n % NF) + 1)}')
  else
    __f=$(printf '%s\n' "| / - \\" | awk -v n="$SPIN_N" '{print $((n % NF) + 1)}')
  fi
  printf '\r%s %s ' "$SPIN_LABEL" "$__f"
}
spin_end() {
  if [ -n "$SPIN_ON" ]; then printf '\r\033[K'; fi
  SPIN_ON=""
}

need_check() { # every command of need_list looked up, before anything is changed; a missing required one stops here
  local __all __l __k __c __w __miss="" __opt="" __n=0 __nl
  __nl=$(printf '\nx')
  __nl=${__nl%x}
  __all=$(need_list) # no here-document: bash 3.2 writes those to /tmp, which can be full
  spin_start "Checking dependencies..."
  while [ -n "$__all" ]; do
    __l=${__all%%"$__nl"*}
    case "$__all" in *"$__nl"*) __all=${__all#*"$__nl"} ;; *) __all="" ;; esac
    __k=${__l%% *}
    __l=${__l#* }
    __c=${__l%% *}
    __w=${__l#* }
    __n=$((__n + 1))
    spin_tick
    if need_have "$__c"; then continue; fi
    case "$__k" in
      p) ;;
      r | R) __miss="$__miss
$__c: $__w" ;;
      *) __opt="$__opt
$__c: without it, $__w" ;;
    esac
  done
  spin_end
  logf "need_check: $__n commands looked up; missing required:$(printf '%s' "$__miss" | awk -F: 'NF {printf " %s", $1}'); missing optional:$(printf '%s' "$__opt" | awk -F: 'NF {printf " %s", $1}')"
  if [ -n "$__miss" ]; then
    err "This NAS lacks commands the repair cannot do without:"
    printf '%s\n' "$__miss" | grep . | while IFS= read -r __w; do note "$__w"; done
    note "Nothing was changed. The PATH searched: $PATH"
    return 1
  fi
  if [ -n "$__opt" ]; then
    say "Not on this NAS (the script goes on without them):"
    printf '%s\n' "$__opt" | grep . | while IFS= read -r __w; do note "$__w"; done
  fi
  ok "Checked $__n commands: everything the repair needs is on this NAS."
  return 0
}

# selftest: known answers from the commands this script relies on, and the storage tools asked for their version.
# Read-only: it writes only into a temporary folder of its own in the log directory, and removes it.
st_one() { # st_one "what" "expected" "got": one result into ST_OK / ST_BAD
  spin_tick
  if [ "$3" = "$2" ]; then
    ST_OK=$((ST_OK + 1))
    logf "selftest ok: $1"
  else
    ST_BAD="$ST_BAD
$1|$2|$3"
    logf "selftest FAILED: $1: expected '$2', got '$3'"
  fi
}
st_has() { # st_has "what" "word" command...: the command's output must contain the word
  local __w=$1 __x=$2 __o
  shift 2
  if ! have "$1" && [ ! -x "$1" ]; then
    ST_SKIP="$ST_SKIP $__w"
    return 0
  fi
  __o=$("$@" 2>&1 | head -n 40)
  case "$__o" in
    *"$__x"*) st_one "$__w" "answers" "answers" ;;
    *) st_one "$__w" "output with '$__x'" "$(printf '%s' "$__o" | head -n 1 | cut -c1-40)" ;;
  esac
}
selftest() {
  local __d __p
  ST_OK=0
  ST_BAD=""
  ST_SKIP=""
  __d="${LOGDIR:-$TMPD}/selftest.$$"
  mkdir -p "$__d" || {
    err "No room for the self-test files in ${LOGDIR:-$TMPD}."
    return 1
  }
  hdr "Self-test of the commands this script uses (read-only)"
  spin_start "Testing tools..."
  st_one "awk -F, printf, index, substr" "b-5-a" "$(echo 'a|b|c' | awk -F'|' '{printf "%s-%d-%s", $2, index($0, "c"), substr($0, 1, 1)}')"
  st_one "awk sprintf" "007|1.5" "$(awk 'BEGIN {printf "%s", sprintf("%03d|%.1f", 7, 1.5)}')"
  st_one "sed address range" "a b c " "$(printf 'x\na\nb\nc\ny\n' | sed -n '/a/,/c/p' | tr '\n' ' ')"
  st_one "sed s///" "aXc" "$(echo abc | sed 's/b/X/')"
  st_one "grep -E -q" "y" "$(echo foo123 | grep -Eq '^foo[0-9]+$' && echo y)"
  printf 'a\nb\n' >"$__d/f1"
  printf 'a\nc\n' >"$__d/f2"
  st_one "diff -U" "2" "$(diff -U0 "$__d/f1" "$__d/f2" | grep -c '^[-+][bc]$')"
  st_one "cmp -s" "same differ" "$(cmp -s "$__d/f1" "$__d/f1" && echo same) $(cmp -s "$__d/f1" "$__d/f2" || echo differ)"
  st_one "sort -n" "9 10 100 " "$(printf '10\n9\n100\n' | sort -n | tr '\n' ' ')"
  st_one "date +%s" "y" "$(date +%s | awk '$1 > 1700000000 {print "y"}')"
  dd if=/dev/zero "of=$__d/z" bs=1024 count=3 2>/dev/null
  st_one "dd bs count" "3072" "$(fsize "$__d/z")"
  printf 'hello' | gzip -c >"$__d/h.gz" 2>/dev/null
  st_one "gzip -c, -t, -dc" "hello" "$(gzip -t "$__d/h.gz" 2>/dev/null && gzip -dc "$__d/h.gz")"
  if have sha256sum; then
    st_one "sha256sum" "ba7816bf" "$(printf 'abc' | sha256sum | cut -c1-8)"
  else
    st_one "md5sum" "90015098" "$(printf 'abc' | md5sum | cut -c1-8)"
  fi
  st_one "printf %s" "a b" "$(printf '%s %s' a b)"
  st_has "lvs --version" "LVM version" lvs --version
  st_has "dmsetup version" "Library version" dmsetup version
  st_has "mdadm --version" "mdadm" mdadm --version
  for __p in pdata_tools_8192 pdata_tools_4096; do
    if have "$__p"; then st_has "$__p thin_check -V" "." "$__p" thin_check -V; fi
  done
  if have e2fsck_64; then st_has "e2fsck_64 -V" "e2fsck" e2fsck_64 -V; else st_has "e2fsck -V" "e2fsck" e2fsck -V; fi
  st_has "cryptsetup --version" "cryptsetup" cryptsetup --version
  st_has "storage_util --help" "sys_startup_p2" storage_util --help
  st_has "screen -v" "Screen version" screen -v
  spin_end
  rm -rf "$__d"
  if [ -n "$ST_BAD" ]; then
    printf '%s\n' "$ST_BAD" | grep . | while IFS='|' read -r __p __d __w; do
      err "$__p: expected $__d, got '$__w'"
    done
  fi
  if [ -n "$ST_SKIP" ]; then note "Not on this NAS, not tested:$ST_SKIP"; fi
  if [ -z "$ST_BAD" ]; then
    ok "Self-test: all $ST_OK checks passed."
    return 0
  fi
  warn "Self-test: $(printf '%s\n' "$ST_BAD" | grep -c .) check(s) failed, $ST_OK passed."
  note "A command that does not work as expected can break a step half way."
  note "Ask at forum.qnap.net.pl before a repair, with the logs (7) Logs -> p)."
  return 1
}

# The record of changes: every command that changes the storage stack or the services, as it runs, with its exit
# code and how to undo it at that point (changes.log in the log directory; report.txt lists it). Nothing is printed
# at the command: a busy umount or lvmetad's stop can fail on purpose. Where a step really fails (the FAILED or
# CRITICAL banner) chg_summary shows the last failed change, what was changed before it and the way back.
chg_undo() { # chg_undo <command...>: the undo of a command that changes the system; nothing for one that does not
  local __c="$*" __last=""
  for __last in "$@"; do :; done
  case "$__c" in
    umount\ *) echo "step 5 mounts it again (storage_util --sys_startup_p2)" ;;
    mount\ *) echo "umount $__last" ;;
    kill\ -9\ *) echo "none: the stopped programs start again with the services (step 5)" ;;
    dmsetup\ remove\ *) echo "step 5 builds it again (storage_util --sys_startup_p2)" ;;
    cryptsetup\ luksClose\ *) echo "unlock the volume again in Storage & Snapshots after step 5" ;;
    swapoff\ *) echo "swapon $__last" ;;
    "lvchange -ky "*) echo "lvchange -kn $__last" ;;
    "lvchange -kn "*) echo "lvchange -ky $__last" ;;
    "lvchange -an "* | "vgchange -an "*) echo "${__c%% *} -ay $__last (step 5 brings the pool up)" ;;
    "lvchange -ay "* | "vgchange -ay "*) echo "${__c%% *} -an $__last (step 2 takes the pool offline)" ;;
    vgcfgrestore\ *) echo "vgcfgrestore with the other configuration saved in the logs (6) Tools -> c) for the swap)" ;;
    vgextend\ *) echo "none by command: vgcfgrestore with the copy from before ($WORKDIR)" ;;
    *thin_repair*"-o $METADEV"* | *thin_restore*"-o $METADEV"* | *thin_patch*"$METADEV"* | *thin_rebuild* | \
      *"of=$METADEV"* | "gz_restore "*"$METADEV" | *"--clear-needs-check-flag"*)
      echo "none by command: 6) Tools -> d) writes the image ${BACKUP_FILE:-of step 3} back"
      ;;
    *thin_repair*"-o $TMPDEV"* | *thin_restore*"-o $TMPDEV"* | *thin_ll_restore*)
      echo "none needed: $TMPLV holds only the working copy"
      ;;
    *e2fsck*-fy* | *e2fsck*-fp*) echo "none: e2fsck changed the filesystem" ;;
    *services.sh\ stop | *qsnapman.sh\ stop | *iscsitrgt.sh\ stop) echo "${__c% stop} start" ;;
    *qulog.sh\ force-stop) echo "${__c% force-stop} start (or a NAS reboot)" ;;
    *services.sh\ start | *qsnapman.sh\ start | *iscsitrgt.sh\ start) echo "${__c% start} stop" ;;
    *daemon_mgr*\ stop\ *) echo "$1 lvmetad start /sbin/lvmetad" ;;
    *daemon_mgr*\ start\ *) echo "$1 lvmetad stop /sbin/lvmetad" ;;
    *init_lvm.sh) echo "copy the *.$BRINGUP_TAG files from the logs back to $CONFL, then step 5" ;;
    "storage_util --sys_startup_p2"* | "storage_util --volume_scan"*) echo "step 2 takes the pool offline again" ;;
    *--set-rc-seq) echo "none needed: only the start links of the apps" ;;
  esac
}

chg_rec() { # chg_rec <command...>: called for every command with RC set; records the ones that change the system
  local __u
  __u=$(chg_undo "$@")
  if [ -z "$__u" ]; then return 0; fi
  printf '%s | rc=%s | %s | undo: %s\n' "$(ts)" "$RC" "$*" "$__u" 2>/dev/null >>"$LOGDIR/changes.log"
}

chg_summary() { # under a FAILED or CRITICAL banner: the last failed change, what was changed before, the way back
  local __l __n
  if [ ! -d "$LOGDIR" ]; then # the work directory's disk is gone: the list is there, out of reach for now
    say "The list of what this session changed is in $LOGDIR/changes.log, which cannot be read now."
    return 0
  fi
  if [ ! -s "$LOGDIR/changes.log" ]; then
    say "This session has changed nothing on the NAS yet."
    return 0
  fi
  __l=$(awk -F' [|] ' 'NF >= 4 && $2 != "rc=0" {l = $3 " (" $2 ")"} END {print l}' "$LOGDIR/changes.log" 2>/dev/null)
  if [ -n "$__l" ]; then say "The last command that failed while changing the NAS: $__l"; fi
  say "Changed so far in this session, newest first, and the way back:"
  awk -F' [|] ' 'NF >= 4 && $2 == "rc=0" {l[++n] = $3 "  ->  " $4} END {for (i = n; i > n - 5 && i > 0; i--) print l[i]}' \
    "$LOGDIR/changes.log" 2>/dev/null | while IFS= read -r __l; do note "$__l"; done
  __n=$(grep -c ' | rc=0 | ' "$LOGDIR/changes.log" 2>/dev/null)
  if [ "${__n:-0}" -gt 5 ]; then note "(all $__n in $LOGDIR/changes.log; report.txt lists them too)"; fi
}

# ==================================================================================================
#  Call trace and debug mode
#    Every step function runs through a wrapper that keeps the call stack (STACK). The log always
#    gets the enter/leave lines. With --debug they are shown on the screen too, every command is
#    framed with its number, time, call stack, exit code and duration, and a full shell trace
#    (set -x) goes to trace.log in the work directory.
# ==================================================================================================
dbg() { # a trace remark: always logged, shown only in debug mode
  logf "  . $*"
  if [ -n "$DEBUG" ]; then printf '%s%s. %s%s\n' "$C_D" "$IND" "$*" "$C_0"; fi
}

_enter() { # $1 = function, the rest = its arguments
  STACK="${STACK:+$STACK > }$1"
  logf "  > $*"
  if [ -n "$DEBUG" ]; then printf '%s%s> %s%s\n' "$C_D" "$IND" "$*" "$C_0"; fi
  IND="$IND  "
}

_leave() { # $1 = return code, $2 = function
  IND=${IND%  }
  logf "  < $2 = $1"
  if [ -n "$DEBUG" ]; then printf '%s%s< %s = %s%s\n' "$C_D" "$IND" "$2" "$1" "$C_0"; fi
  case "$STACK" in *" > "*) STACK=${STACK% > *} ;; *) STACK="" ;; esac
  return "$1"
}

_wrap() { # _wrap name...: the body is defined as _<name>; the public name becomes the traced wrapper
  local __f
  for __f in "$@"; do
    eval "$__f() { _enter $__f \"\$@\"; _$__f \"\$@\"; _leave \$? $__f; }"
  done
}

trace_on() { # full shell trace into trace.log; only with a work directory, never into /tmp or md9
  if [ -n "$TRACE_ON" ] || [ -n "$OUT_CAP" ]; then return 0; fi
  exec 9>&2
  exec 2>>"$LOGDIR/trace.log"
  PS4='+[$LINENO] '
  TRACE_ON=1
  set -x
}

trace_off() {
  if [ -z "$TRACE_ON" ]; then return 0; fi
  { set +x; } 2>/dev/null
  exec 2>&9 9>&-
  TRACE_ON=""
}

set_cap() { # no work directory: the logs sit on md9 or in /tmp, both small (/tmp is a 64 MB tmpfs, filling it takes the NAS down)
  if [ -n "$WORKDIR" ] && [ "$LOGDIR" = "$WORKDIR/logs" ]; then OUT_CAP=""; else OUT_CAP=20000; fi
}

# ==================================================================================================
#  Running commands (each one is logged with its number, call stack, exit code and duration)
# ==================================================================================================
_cmd_head() {
  CMD_SEQ=$((CMD_SEQ + 1))
  if [ -n "$DEBUG" ]; then
    printf '%s+--[%s] %s  %s%s\n' "$C_D" "$CMD_SEQ" "$(date +%H:%M:%S)" "${STACK:-main}" "$C_0"
    printf '%s| $ %s%s\n' "$C_B" "$*" "$C_0"
  else
    printf '\n%s$ %s%s\n' "$C_D" "$*" "$C_0"
  fi
  logf "[$CMD_SEQ] (${STACK:-main}) \$ $*"
}

_show() { # _show <from> <to|$> [file]: print that line range of the current command output
  if [ -n "$DEBUG" ]; then
    sed -n "$1,$2s/^/|   /p" "${3:-$LOGDIR/cmd.out}"
  else
    sed -n "$1,$2p" "${3:-$LOGDIR/cmd.out}"
  fi
}

_cmd_done() { # $1 = start time, the rest = the command
  local __t0=$1 __t1
  shift
  __t1=$(date +%s)
  cat "$LOGDIR/cmd.out" 2>/dev/null >>"$LOG"
  printf '%s | rc=%s | %ss | %s | %s\n' "$(ts)" "$RC" "$((__t1 - __t0))" "${STACK:-main}" "$*" 2>/dev/null >>"$CMDLOG"
  logf "[$CMD_SEQ] rc=$RC ($(fmt_dur $((__t1 - __t0))))"
  chg_rec "$@"
  if [ -n "$DEBUG" ]; then
    printf '%s+--[%s] rc=%s  %s%s\n' "$C_D" "$CMD_SEQ" "$RC" "$(fmt_dur $((__t1 - __t0)))" "$C_0"
  elif [ "$RC" != 0 ]; then
    printf '%s    -> exit code %s   (in: %s)%s\n' "$C_Y" "$RC" "${STACK:-main}" "$C_0"
  fi
  if [ -n "$OUT_CAP" ] && [ "$(fsize "$LOG" | awk '{print ($1 > 4194304) ? 1 : 0}')" = 1 ]; then
    tail -n 2000 "$LOG" 2>/dev/null >"$LOG.tmp" && mv -f "$LOG.tmp" "$LOG"
  fi
}

run() { # short command: the output is shown when it ends
  local __t0
  _cmd_head "$@"
  __t0=$(date +%s)
  (
    { set +x; } 2>/dev/null
    umask "$UMASK0"
    "$@"
  ) >"$LOGDIR/cmd.out" 2>&1
  RC=$?
  _show 1 '$'
  _cmd_done "$__t0" "$@"
  return "$RC"
}

runq() { # like run, but nothing is printed on the screen
  local __t0
  CMD_SEQ=$((CMD_SEQ + 1))
  logf "[$CMD_SEQ] (${STACK:-main}) \$ $*"
  __t0=$(date +%s)
  (
    { set +x; } 2>/dev/null
    umask "$UMASK0"
    "$@"
  ) >"$LOGDIR/cmd.out" 2>&1
  RC=$?
  _cmd_done "$__t0" "$@" >/dev/null
  return "$RC"
}

# Long command: runs in the background, detached from the terminal (Ctrl+C and a dropped
# SSH session do not interrupt it); the output is shown live with an elapsed-time counter.
#   RL_SAVE=file   an extra copy of the output
#   RL_WATCH=file  show the size of that file (dd progress), RL_TOTAL=MiB
#   RL_READ=file   it holds a PID: the bar counts the bytes that process has read (/proc/PID/io), of RL_TOTAL
#   RL_CRIT=1      ignore SIGTERM as well (metadata writes); its output is never piped
#   RL_DAEMON=1    the command can leave a daemon behind, and the daemon keeps the output file open: the output
#                  goes to a file in $TMPD and is copied into cmd.out at the end, so the work disk can be unmounted
run_long() {
  local __t0 __pid __shown __n __el __tick __st __cur __rd __o="$LOGDIR/cmd.out"
  _cmd_head "$@"
  : >"$LOGDIR/cmd.out"
  rm -f "$RCF"
  if [ -n "$RL_DAEMON" ]; then
    __o="$RCF.out"
    rm -f "$__o" # a new file every time: a daemon of an earlier command may still write to the last one
    : >"$__o"
  fi
  __t0=$(date +%s)
  (
    { set +x; } 2>/dev/null
    umask "$UMASK0"
    trap '' INT QUIT HUP
    if [ -n "$RL_CRIT" ]; then trap '' TERM; fi
    if [ -n "$RL_DAEMON" ]; then exec </dev/null; fi
    if [ -n "$OUT_CAP" ] && [ -z "$RL_CRIT" ] && [ -z "$RL_DAEMON" ]; then
      {
        "$@" 2>&1
        echo $? >"$RCF.cmd"
      } | awk -v m="$OUT_CAP" '
        NR <= m
        NR == m + 1 { print "... output cut after " m " lines: no work directory, the logs sit on md9 or in /tmp (both small)" }
      ' >"$LOGDIR/cmd.out"
      cat "$RCF.cmd" >"$RCF"
    else
      "$@" >"$__o" 2>&1
      echo $? >"$RCF"
    fi
  ) &
  __pid=$!
  __shown=0
  __tick=0
  __st=""
  while [ ! -f "$RCF" ] && kill -0 "$__pid" 2>/dev/null; do
    sleep "$POLL"
    __tick=$((__tick + 1))
    __n=$(wc -l <"$__o" 2>/dev/null)
    __n=$((__n + 0))
    if [ "$__n" -gt "$__shown" ]; then
      if [ -n "$__st" ]; then
        printf '\r\033[K'
        __st=""
      fi
      _show "$((__shown + 1))" "$__n" "$__o"
      __shown=$__n
    fi
    if [ -n "$IS_TTY" ] && [ $((__tick % 5)) = 0 ]; then
      __el=$(($(date +%s) - __t0))
      __st="    ... running $(fmt_dur "$__el")"
      if [ -n "$RL_WATCH" ] && [ -f "$RL_WATCH" ]; then
        __cur=$(fsize "$RL_WATCH" | awk '{printf "%d", $1/1048576}')
        __rd=""
        if [ -n "$RL_READ" ] && [ "${RL_TOTAL:-0}" -gt 0 ] 2>/dev/null; then
          __rd=$(awk '$1 == "rchar:" {printf "%d", $2 / 1048576}' "/proc/$(cat "$RL_READ" 2>/dev/null)/io" 2>/dev/null)
        fi
        if [ -n "$__rd" ]; then
          __st="    $(progress_bar "$__rd" "$RL_TOTAL" "$__el")"
        elif [ -n "$RL_TOTAL" ] && [ -z "$RL_READ" ]; then
          __st="    $(progress_bar "$__cur" "$RL_TOTAL" "$__el")"
        else
          __st="$__st, written $__cur MiB"
        fi
      fi
      printf '\r\033[K%s' "$__st"
    fi
  done
  wait "$__pid" 2>/dev/null
  if [ -n "$__st" ]; then printf '\r\033[K'; fi
  if [ -n "$RL_DAEMON" ]; then
    if [ -n "$OUT_CAP" ]; then head -n "$OUT_CAP" "$__o"; else cat "$__o"; fi 2>/dev/null >"$LOGDIR/cmd.out"
    rm -f "$__o"
  fi
  _show "$((__shown + 1))" '$'
  RC=$(cat "$RCF" 2>/dev/null)
  RC=${RC:-255}
  if [ -n "$RL_SAVE" ]; then cp "$LOGDIR/cmd.out" "$RL_SAVE" 2>/dev/null; fi
  _cmd_done "$__t0" "$@"
  return "$RC"
}

run_daemon() { # run_long for a command that can leave a daemon behind: init scripts, storage_util, daemon_mgr
  RL_DAEMON=1
  run_long "$@"
  RL_DAEMON=""
  return "$RC"
}

ls_head() { ls -la "$1" | head -n 40; }
show_mounts() { grep -E 'CACHEDEV|/mnt/pool' "$F_MOUNTS"; }
dd_gzip() { { # dd runs as a job of its own, so that run_long can show how far it has read (RL_READ)
  dd "if=$1" bs=4194304 2>"$LOGDIR/dd-gzip.err" &
  echo $! >"$RCF.ddpid"
  wait $!
  echo $? >"$RCF.dd"
  rm -f "$RCF.ddpid"
} | gzip -1 >"$2"; }
gz_size() { gzip -dc "$1" | wc -c; }
gz_restore() { gzip -dc "$1" | dd "of=$2" bs=4194304; }

progress_bar() { # progress_bar <done MiB> <total MiB> <elapsed s>: bar, percent, rate and time left
  awk -v c="$1" -v t="$2" -v e="$3" 'BEGIN {
    if (t <= 0) exit
    p = c / t; if (p > 1) p = 1
    n = int(p * 24); bar = ""
    for (i = 0; i < 24; i++) bar = bar (i < n ? "#" : ".")
    r = (e > 0) ? c / e : 0
    eta = (r > 0) ? int((t - c) / r) : 0
    printf "[%s] %3d%%  %d/%d MiB  %d MiB/s  left %02d:%02d:%02d", bar, p * 100, c, t, r, eta / 3600, eta % 3600 / 60, eta % 60
  }'
}

lvmetad_refresh() { # after vgcfgrestore: a running lvmetad re-reads the PV headers (LVM header SOP)
  if [ -e /var/run/lvm/lvmetad.socket ] && have pvscan; then runq pvscan --cache; fi
}

file_digest() { # "sha256 <hex>" (or md5) of a file; empty when the NAS has no checksum tool
  if have sha256sum; then
    sha256sum "$1" 2>/dev/null | awk '{print "sha256 " $1}'
  elif have md5sum; then
    md5sum "$1" 2>/dev/null | awk '{print "md5 " $1}'
  fi
}

# trust_file <file> <pinned sha256 or empty> <what it is>: a downloaded helper runs as admin, so it is
# shown with its checksum first; with a pinned value it must match, without one the operator decides.
trust_file() {
  local __d
  __d=$(file_digest "$1")
  say "$3: $1 ($(fsize "$1") B, ${__d:-no checksum tool on this NAS})"
  if [ -n "$2" ]; then
    if [ "$__d" = "sha256 $2" ]; then
      ok "The checksum matches the pinned value."
      return 0
    fi
    err "The checksum differs from the pinned value - not running it."
    return 1
  fi
  if [ -n "$AUTO" ]; then return 1; fi
  ask_yn "It came over the network and matches no pinned checksum. Run it?" n
}

# same_data <image> <device> [gz]: byte-for-byte comparison; 0 same, 1 different, 2 nothing to compare with
same_data() {
  local __a __b
  if have cmp; then
    if [ "$3" = gz ]; then gzip -dc "$1" | cmp -s - "$2"; else cmp -s "$1" "$2"; fi
    return $?
  fi
  if have md5sum; then
    if [ "$3" = gz ]; then __a=$(gzip -dc "$1" | md5sum); else __a=$(md5sum <"$1"); fi
    __b=$(md5sum <"$2")
    [ "${__a%% *}" = "${__b%% *}" ]
    return $?
  fi
  return 2
}

# init_has <script> <verb>: does the init script's case accept that verb? (on QTS the first
# argument of many init scripts is data, not a verb)
init_has() {
  [ -r "$1" ] && grep -Eq "^[[:space:]]*([\"']?[a-z_-]+[\"']?\|)*[\"']?$2[\"']?(\|[\"']?[a-z_-]+[\"']?)*\)" "$1"
}

# 0 when the path sits on a mounted block-device filesystem: not the RAM disk, not a tmpfs, not md9/md13.
# An unplugged USB disk leaves its folder behind in RAM, and a copy into it fills RAM, not the disk.
on_data_mount() {
  awk -v p="$1/" '
    { m = $2; if (m != "/") m = m "/"
     if (index(p, m) == 1 && length(m) >= best) { best = length(m); src = $1; fs = $3; mp = $2 } }
    END { exit !(src ~ /^\/dev\// && src !~ /^\/dev\/(md9|md13|ram|loop|mmcblk)/ && fs != "tmpfs" && mp != "/") }
  ' "$F_MOUNTS"
}

_sec() {
  printf '\n----- %s\n' "$*"
  "$@"
}

snapshot() { # snapshot label - full state dump (RAID, LVM, dm, mounts) + dmesg
  local __f="$LOGDIR/state-$(date +%H%M%S)-$1.txt"
  if [ -n "$OUT_CAP" ]; then rm -f "$LOGDIR"/state-* "$LOGDIR"/dmesg-* 2>/dev/null; fi
  (
    { set +x; } 2>/dev/null
    printf '### %s  %s\n' "$(ts)" "$1"
    _sec uname -a
    _sec cat "$F_MDSTAT"
    if [ -r /proc/drbd ]; then _sec cat /proc/drbd; fi
    _sec pvs -a
    _sec vgs
    _sec lvs -a
    _sec lvs -a -o+thin_id
    _sec dmsetup ls --tree
    _sec dmsetup info -c
    _sec dmsetup status
    _sec cat "$F_MOUNTS"
    _sec cat "$F_SWAPS"
    _sec df -h
  ) >"$__f" 2>&1
  # dmesg carries the kernel messages and call traces (device-mapper thin, I/O)
  dmesg >"$LOGDIR/dmesg-$(date +%H%M%S)-$1.txt" 2>&1
  logf "State dump saved: $__f"
}

# ==================================================================================================
#  Session state, lock, exit
# ==================================================================================================
state_val() { # the value of one saved variable by name: an explicit list, nothing is evaluated
  case "$1" in
    VG) printf '%s' "$VG" ;;
    POOL) printf '%s' "$POOL" ;;
    META) printf '%s' "$META" ;;
    TMPLV) printf '%s' "$TMPLV" ;;
    PDATA) printf '%s' "$PDATA" ;;
    WORKDIR) printf '%s' "$WORKDIR" ;;
    STAGE) printf '%s' "$STAGE" ;;
    CLASS) printf '%s' "$CLASS" ;;
    RPATH) printf '%s' "$RPATH" ;;
    SERVICES_STOPPED) printf '%s' "$SERVICES_STOPPED" ;;
    QSNAP_STOPPED) printf '%s' "$QSNAP_STOPPED" ;;
    BACKUP_FILE) printf '%s' "$BACKUP_FILE" ;;
    BACKUP_KIND) printf '%s' "$BACKUP_KIND" ;;
    XML_OK) printf '%s' "$XML_OK" ;;
    NOBACKUP) printf '%s' "$NOBACKUP" ;;
    DATA_ACK) printf '%s' "$DATA_ACK" ;;
    AFFECTED) printf '%s' "$AFFECTED" ;;
    DIAG_TC) printf '%s' "$DIAG_TC" ;;
    FSCK) printf '%s' "$FSCK" ;;
    COPY_LIVE) printf '%s' "$COPY_LIVE" ;;
    TIERS_USED) printf '%s' "$TIERS_USED" ;;
    STARTED) printf '%s' "$STARTED" ;;
  esac
}

save_state() { # plain KEY=value lines, written to a temporary file and renamed over the old one
  local __f __v
  for __f in "$PERSIST/state" "${WORKDIR:+$WORKDIR/state}"; do
    [ -n "$__f" ] || continue
    # the work directory is away (drive unplugged): md9 keeps the state
    if [ "$__f" != "$PERSIST/state" ] && [ ! -d "$WORKDIR" ]; then continue; fi
    if [ "$STAGE" = "done" ] && [ "$__f" = "$PERSIST/state" ] && [ ! -e "$__f" ]; then continue; fi
    { for __v in $STATE_VARS; do printf '%s=%s\n' "$__v" "$(state_val "$__v")"; done; } >"$__f.tmp" 2>/dev/null &&
      mv -f "$__f.tmp" "$__f" 2>/dev/null
  done
}

state_ok() { # state_ok <kind> <value>: is a saved value well-formed?
  case "$1" in
    name) case "$2" in '' | *[!A-Za-z0-9_.+-]*) return 1 ;; esac ;;
    oname) case "$2" in *[!A-Za-z0-9_.+-]*) return 1 ;; esac ;;
    path) case "$2" in
      '') ;;
      /*) case "$2" in *[!A-Za-z0-9_./-]*) return 1 ;; esac ;;
      *) return 1 ;;
    esac ;;
    flag) case "$2" in '' | 1) ;; *) return 1 ;; esac ;;
  esac
  return 0
}

load_state() { # the saved session is read as data: known keys only, every value checked, nothing executed
  local __k __v __bad=""
  while IFS='=' read -r __k __v; do
    case "$__v" in \"*\")
      __v=${__v#\"}
      __v=${__v%\"}
      ;;
    esac # files written by versions up to 1.3
    case "$__k" in
      VG) if state_ok name "$__v"; then VG=$__v; else __bad=$__k; fi ;;
      POOL) if state_ok name "$__v"; then POOL=$__v; else __bad=$__k; fi ;;
      META) if state_ok name "$__v"; then META=$__v; else __bad=$__k; fi ;;
      TMPLV) if state_ok oname "$__v"; then TMPLV=$__v; else __bad=$__k; fi ;;
      PDATA) if state_ok oname "$__v" || state_ok path "$__v"; then PDATA=$__v; else __bad=$__k; fi ;;
      WORKDIR) if state_ok path "$__v"; then WORKDIR=$__v; else __bad=$__k; fi ;;
      STAGE) case "$__v" in
        new | offline | diagnosed | backed_up | tmp_ok | swapped | verified | final_started | final_ok | done) STAGE=$__v ;;
        *) __bad=$__k ;;
      esac ;;
      CLASS) case "$__v" in '' | CLEAN | SPACEMAP | MAPPING | SUPERBLOCK | UNKNOWN) CLASS=$__v ;; *) __bad=$__k ;; esac ;;
      RPATH) case "$__v" in '' | quick | full | legacy | rebuild | flag | superblock) RPATH=$__v ;; *) __bad=$__k ;; esac ;;
      SERVICES_STOPPED) if state_ok flag "$__v"; then SERVICES_STOPPED=$__v; else __bad=$__k; fi ;;
      QSNAP_STOPPED) if state_ok flag "$__v"; then QSNAP_STOPPED=$__v; else __bad=$__k; fi ;;
      BACKUP_FILE) if state_ok path "$__v"; then BACKUP_FILE=$__v; else __bad=$__k; fi ;;
      BACKUP_KIND) case "$__v" in '' | raw | gz) BACKUP_KIND=$__v ;; *) __bad=$__k ;; esac ;;
      XML_OK) if state_ok flag "$__v"; then XML_OK=$__v; else __bad=$__k; fi ;;
      NOBACKUP) if state_ok flag "$__v"; then NOBACKUP=$__v; else __bad=$__k; fi ;;
      DATA_ACK) case "$__v" in '' | yes | no) DATA_ACK=$__v ;; *) __bad=$__k ;; esac ;;
      AFFECTED) case "$__v" in *[!A-Za-z0-9_.+\ -]*) __bad=$__k ;; *) AFFECTED=$__v ;; esac ;;
      DIAG_TC) if state_ok oname "$__v"; then DIAG_TC=$__v; else __bad=$__k; fi ;;
      FSCK) case "$__v" in '' | done | skip) FSCK=$__v ;; *) __bad=$__k ;; esac ;;
      COPY_LIVE) if state_ok flag "$__v"; then COPY_LIVE=$__v; else __bad=$__k; fi ;;
      TIERS_USED) case "$__v" in '' | [0-9] | [0-9][0-9]) TIERS_USED=$__v ;; *) __bad=$__k ;; esac ;;
      STARTED) case "$__v" in *[!0-9:\ -]*) __bad=$__k ;; *) STARTED=$__v ;; esac ;;
      '') ;;
      *) __bad=$__k ;;
    esac
  done <"$PERSIST/state"
  if [ -n "$__bad" ]; then
    logf "saved session refused: bad key or value at '$__bad'"
    return 1
  fi
  return 0
}

set_stage() {
  STAGE=$1
  save_state
  logf "STAGE -> $STAGE"
}

stage_num() {
  case "$1" in
    new) echo 0 ;; offline) echo 1 ;; diagnosed) echo 2 ;; backed_up) echo 3 ;;
    tmp_ok) echo 4 ;; swapped) echo 5 ;; verified) echo 6 ;;
    final_started) echo 7 ;; final_ok) echo 8 ;; done) echo 9 ;; *) echo 0 ;;
  esac
}
stage_ge() { [ "$(stage_num "$STAGE")" -ge "$(stage_num "$1")" ]; }

stage_desc() {
  case "$1" in
    new) echo "start" ;;
    offline) echo "pool offline" ;;
    diagnosed) echo "diagnosed" ;;
    backed_up) echo "backup done" ;;
    tmp_ok) echo "repaired copy on the scratch LV (verified)" ;;
    swapped) echo "LVM TEMPORARILY points at the working copy (test mount)" ;;
    verified) echo "data confirmed on the working copy" ;;
    final_started) echo "WRITE to the original tmeta started / interrupted" ;;
    final_ok) echo "original tmeta repaired and verified" ;;
    done) echo "finished" ;;
    *) echo "$1" ;;
  esac
}

lock_take() {
  local __p
  LOCKDIR="$TMPD/$SESSION.lock" # in /tmp, not on md9: a lock must be gone after a reboot
  if ! mkdir "$LOCKDIR" 2>/dev/null; then
    __p=$(cat "$LOCKDIR/pid" 2>/dev/null)
    if [ -n "$__p" ] && kill -0 "$__p" 2>/dev/null; then
      echo "The script is already running (PID $__p). Reattach: screen -U -r $SESSION"
      LOCKDIR=""
      exit 1
    fi
  fi
  echo $$ >"$LOCKDIR/pid"
}

safe_exit() {
  if [ -n "$LOCKDIR" ]; then
    rm -rf "$LOCKDIR"
    LOCKDIR=""
  fi
  if [ -n "$IN_SCREEN" ] && [ "$1" != 3 ]; then
    printf '[Enter] closes the screen window... '
    read -r ANS
  fi
  exit "$1"
}

# ==================================================================================================
#  LVM / device-mapper helpers
# ==================================================================================================
lvtab() { # table of the LVs in the VG: name|attributes|size MiB|pool
  LVTAB=$(lvs -a --noheadings --units m --nosuffix --separator '|' \
    -o lv_name,lv_attr,lv_size,pool_lv "$VG" 2>/dev/null | sed 's/[][ ]//g')
}
lv_field() { printf '%s\n' "$LVTAB" | awk -F'|' -v n="$1" -v f="$2" '$1==n {print $f; exit}'; }
lv_exists() { [ -n "$(lv_field "$1" 1)" ]; }
lv_size_mb() { lv_field "$1" 3 | awk '{printf "%d", $1}'; }
dm_esc() { printf '%s' "$1" | sed 's/-/--/g'; }
dev_of() { printf '%s/%s-%s' "$DEVMAP" "$VGDM" "$(dm_esc "$1")"; }
dm_list() { dmsetup info -c --noheadings --separator : -o name,major,minor,open 2>/dev/null | grep ':'; }
dm_open() { dm_list | awk -F: -v n="$1" '$1==n {print $4; exit}'; }

# dm devices that belong to the VG, except the LVs named in the arguments
vg_dm_left() {
  local __skip=" " __a
  for __a in "$@"; do __skip="$__skip$VGDM-$(dm_esc "$__a") "; done
  dm_list | awk -F: -v p="$VGDM-" -v s="$__skip" 'index($1,p)==1 && index(s," " $1 " ")==0 {print $1 "(open=" $4 ")"}'
}

is_swapped() {
  lvtab
  [ -n "$TMPLV" ] && lv_exists "${TMPLV}_tmeta"
}

pool_is_online() { # 0 when the pool or one of its volumes/snapshots is active
  lvtab
  printf '%s\n' "$LVTAB" | awk -F'|' -v p="$POOL" \
    '($1==p || $4==p) && substr($2,5,1)=="a" {f=1} END {exit !f}'
}

pool_health() { # health flag of the pool LV (lv_attr, 9th character) in words; uses the current LVTAB
  case "$(lv_field "$POOL" 2)" in
    ????????M*) echo "metadata read-only" ;;
    ????????F*) echo "failed" ;;
    ????????D*) echo "out of data space" ;;
    *) echo "" ;;
  esac
}

_require_offline() {
  if is_swapped; then
    err "LVM is in the temporary state (the pool points at ${TMPLV}_tmeta)."
    if copy_live; then copy_live_note; else note "First: 6) Tools -> c) undo the LVM swap."; fi
    return 1
  fi
  if pool_is_online; then
    err "Pool $VG/$POOL is active. Run step 2) Prepare first."
    return 1
  fi
  return 0
}

_meta_up() { # activate the metadata LV on its own (as tp_collect.sh does)
  METADEV=$(dev_of "$META")
  if is_blk "$METADEV"; then return 0; fi
  run lvchange -ay -ff "$VG/$META"
  if is_blk "$METADEV"; then return 0; fi
  err "Cannot activate $VG/$META ($METADEV)."
  return 1
}

_tmp_up() {
  TMPDEV=$(dev_of "$TMPLV")
  if is_blk "$TMPDEV"; then return 0; fi
  run lvchange -ay "$VG/$TMPLV"
  if is_blk "$TMPDEV"; then return 0; fi
  err "Cannot activate the scratch LV $VG/$TMPLV ($TMPDEV)."
  return 1
}

# ==================================================================================================
#  The LVM layer under the pool: PV in "missing" mode, partial LVs, SSD cache (fcorig)
# ==================================================================================================
lvm_check() { # sets PV_MISSING (devices; "unknown" = no such device), LVM_PARTIAL, LVM_CACHE, CACHE_MODE
  PV_MISSING=$(pvs --noheadings --separator '|' -o pv_name,vg_name,pv_attr 2>/dev/null |
    awk -F'|' -v v="$VG" '{
      n = $1; g = $2; a = $3
      gsub(/^ +| +$/, "", n); gsub(/ /, "", g); gsub(/ /, "", a)
      if (g == v && substr(a, 3, 1) == "m") print (n ~ /unknown/ ? "unknown" : n)
    }')
  lvtab
  LVM_PARTIAL=""
  LVM_CACHE=""
  VG_SKIP=""
  # the pool's own row: a snapshot can carry the flag by itself (stock LVM sets it on thin snapshots)
  if printf '%s\n' "$LVTAB" | awk -F'|' -v p="$POOL" '$1==p && substr($2,10,1)=="k" {f=1} END {exit !f}'; then VG_SKIP=1; fi
  if printf '%s\n' "$LVTAB" | awk -F'|' 'substr($2,9,1)=="p" {f=1} END {exit !f}'; then LVM_PARTIAL=1; fi
  if printf '%s\n' "$LVTAB" | awk -F'|' '$2 ~ /^C/ || $1 ~ /_fcorig$/ {f=1} END {exit !f}'; then LVM_CACHE=1; fi
  cache_mode
}

# The SSD cache type, as QNAP's slides give it (docs/SSD cache.pptx). Configured: ssdcache.conf, section [CG_n],
# mode = 2 read-only, 1 read-write, 4 write-only. Running: "dmsetup status CGnssddev" says WRITE_THROUGH_ENHANCED
# for read-only and WRITE_BACK for read-write and write-only.
# A cache group counts only when it is real: its section has enabled = 1, or the dm device CG<n>ssddev exists.
# A NAS that never had an SSD cache still carries [CG_0] with mode = 2 and enabled = 0 (seen on QTS 6.1.0). The
# type comes from the running device when there is one, else from mode. The file read is QTS's own in
# /etc/config.local; the one in /etc/config only when it is the only one. With several groups rw wins. Never
# run on a NAS with an SSD cache: see the TODO block at the top.
cache_mode() { # sets CACHE_MODE (none | ro | rw | unknown) and CACHE_SRC (the line that named it); uses LVM_CACHE
  local __f __n __m __e __v __all __dm __cg="" __ids
  __f="$CONFL/ssdcache.conf"
  if [ ! -r "$__f" ]; then __f="$CONFD/ssdcache.conf"; fi
  __dm=$(dm_list | awk -F: '$1 ~ /^CG[0-9]+ssddev$/ {print $1}')
  if [ -r "$__f" ]; then # one line per [CG_n] section: n, enabled, mode ("-" = no such key)
    __cg=$(awk '
      function out() { if (s != "") print s, (e == "" ? "-" : e), (m == "" ? "-" : m) }
      /^[ \t]*\[/ {
        out(); s = $0; e = ""; m = ""
        sub(/^[ \t]*\[/, "", s); sub(/\].*$/, "", s)
        if (s ~ /^CG_[0-9]+$/) sub(/^CG_/, "", s); else s = ""
        next
      }
      s != "" && /^[ \t]*(enabled|mode)[ \t]*=/ {
        k = $0; sub(/[ \t]*=.*$/, "", k); gsub(/[ \t]/, "", k)
        v = $0; sub(/^[^=]*=/, "", v); gsub(/[ \t\r"]/, "", v)
        if (k == "enabled") e = v; else m = v
      }
      END { out() }' "$__f" 2>/dev/null)
  fi
  __ids=$({
    printf '%s\n' "$__cg" | awk 'NF {print $1}'
    printf '%s\n' "$__dm" | sed -n 's/^CG\([0-9]*\)ssddev$/\1/p'
  } | sort -un)
  __all=$(
    for __n in $__ids; do
      # no case here: bash 3.2 (QTS's sh) cannot parse a case pattern inside $( )
      if printf '%s\n' "$__dm" | grep -q "^CG${__n}ssddev\$"; then
        __m=$(dmsetup status "CG${__n}ssddev" 2>/dev/null)
        if printf '%s\n' "$__m" | grep -q WRITE_BACK; then
          echo "rw|dmsetup status CG${__n}ssddev: WRITE_BACK"
        elif printf '%s\n' "$__m" | grep -q WRITE_THROUGH_ENHANCED; then
          echo "ro|dmsetup status CG${__n}ssddev: WRITE_THROUGH_ENHANCED"
        else
          echo "unknown|dmsetup status CG${__n}ssddev: no cache type this script knows"
        fi
        continue
      fi
      __e=$(printf '%s\n' "$__cg" | awk -v n="$__n" '$1 == n {print $2; exit}')
      __v=$(printf '%s\n' "$__cg" | awk -v n="$__n" '$1 == n {print $3; exit}')
      if [ "$__e" != 1 ]; then continue; fi # configured once, not in use: not a cache
      if [ "$__v" = 2 ]; then
        echo "ro|$__f [CG_$__n] enabled = 1, mode = 2"
      elif [ "$__v" = 1 ] || [ "$__v" = 4 ]; then
        echo "rw|$__f [CG_$__n] enabled = 1, mode = $__v"
      else
        echo "unknown|$__f [CG_$__n] enabled = 1, mode = $__v"
      fi
    done
  )
  CACHE_MODE=none
  CACHE_SRC=""
  for __m in rw ro unknown; do
    __n=$(printf '%s\n' "$__all" | awk -F'|' -v m="$__m" '$1 == m { print $2; exit }')
    if [ -n "$__n" ]; then
      CACHE_MODE=$__m
      CACHE_SRC=$__n
      return 0
    fi
  done
  if [ -n "$LVM_CACHE" ]; then
    CACHE_MODE=unknown
    CACHE_SRC="LVM shows a cache layer, no cache group names its type"
  fi
}

# The owner's decision of 2026-11-20. A read-write or write-only SSD cache, or Qtier in use: the script does not
# repair such a pool and says where to go; no question, no override. A read-only cache: the condition of QNAP's
# fcorig SOP is asked for, once. Called before step 2 touches anything and before every writing step.
cache_gate() { # 1 = stop
  local __stop=""
  cache_mode
  if [ "$CACHE_MODE" = rw ]; then
    err "Found a read-write or write-only SSD cache: $CACHE_SRC"
    note "Such a cache can hold data that is not on the pool's disks yet. Taking the pool offline or repairing its metadata under such a cache can lose that data."
    __stop=1
  fi
  if [ "${TIERS_USED:-0}" -ge 2 ]; then
    err "Qtier is in use on this pool: data sits in $TIERS_USED tiers."
    note "The pool metadata also carries the tier maps; the repair has never been verified with them."
    __stop=1
  fi
  if [ -n "$__stop" ]; then
    note "This script does not repair such a pool. Stopped here; this step changed nothing."
    if ! pool_is_online; then note "The pool is offline. Step 5 brings it up again as it is (it asks first)."; fi
    note "Next: QNAP support, with the logs: 7) Logs -> p packs them."
    return 1
  fi
  if [ "$CACHE_MODE" = ro ] && [ -z "$CACHE_ACK" ]; then
    warn "A read-only SSD cache is configured: $CACHE_SRC"
    note "QNAP's procedure for a pool with an SSD cache starts only when the SSD cache is removed, or disabled with this pool's volumes deselected from it (in Storage & Snapshots)."
    if ! ask_yn "Is the SSD cache removed, or disabled with this pool's volumes deselected?" n; then
      note "Stopped here; this step changed nothing. Remove or disable the SSD cache in QTS, then run the step again."
      return 1
    fi
    CACHE_ACK=1
  fi
  return 0
}

cache_report() { # the diagnosis: what was found and what the repair does about it
  case "$CACHE_MODE" in
    rw)
      warn "SSD cache: read-write or write-only ($CACHE_SRC)."
      note "This script does not repair a pool with such a cache: step 2 and the repair stop and point to QNAP support."
      ;;
    ro)
      warn "SSD cache: read-only ($CACHE_SRC)."
      note "Before step 2 and before the repair the script asks whether it is removed, or disabled for this pool."
      ;;
    unknown)
      warn "SSD cache: found, type not known ($CACHE_SRC)."
      note "The repair asks before it writes with the cache in place."
      ;;
  esac
}

_lvm_gate() { # 1 = the problem is in LVM under the pool; a metadata repair is not the right step
  lvm_check
  if [ -n "$PV_MISSING" ] || [ -n "$LVM_PARTIAL" ]; then
    err "LVM: PV in 'missing' mode / partial LVs in $VG: $(echo ${PV_MISSING:-?})"
    note "This is the LVM layer, not the pool metadata (symptom: 'Refusing activation of partial LV')."
    note "First: 6) Tools -> i) vgextend --restoremissing, then step 5) brings the pool up."
    return 1
  fi
  return 0
}

# "Thin pool repair prepare": when the volumes cannot be unmounted at all, the VG is flagged to be
# skipped at activation and the NAS rebooted; the pool then stays offline and nothing holds it.
skip_and_reboot() {
  local __s=$SERVICES_STOPPED
  say "Last way to get the pool offline: flag the VG to be skipped at activation, then reboot the NAS."
  note "lvchange -ky $VG   -> after the reboot the pool stays inactive and nothing holds it"
  note "Started again after the reboot, this script clears the flag (lvchange -kn $VG)."
  ask_yn "Set the flag now?" n || return 1
  # QTS then boots with the pool down and does not start the apps on it: step 5 has to, so it is recorded first
  SERVICES_STOPPED=1
  save_state
  if ! run lvchange -ky "$VG"; then
    SERVICES_STOPPED=$__s
    save_state
    return 1
  fi
  lvm_check
  warn "Reboot the NAS now (the script does not do that), then start the script again."
  return 0
}

clear_skip_flag() { # the counterpart: run once the pool is offline after that reboot; never in the temporary state
  if is_swapped; then return 0; fi
  lvm_check
  if [ -z "$VG_SKIP" ]; then return 0; fi
  say "VG $VG carries the skip-activation flag (it keeps the pool offline over a reboot)."
  say "Clearing it now - that activates nothing by itself."
  run lvchange -kn "$VG"
}

# The temporary state (pool on the working copy) must not meet a reboot unguarded: QTS would start the pool
# read-write on the copy and the apps would write through it. So the VG carries the skip-activation flag for
# as long as LVM is swapped. vgcfgrestore replaces the whole configuration, flags included: the swapped file
# is made from the flagged configuration (path_swap_test), the restore of the original takes the flag off.
# swap_guard checks that the flag is there and sets it when it is not (a swap left by version 1.5).
swap_guard() {
  if ! is_swapped; then return 0; fi
  lvm_check
  if [ -z "$VG_SKIP" ]; then
    run lvchange -ky "$VG"
    lvm_check
  fi
  if [ -n "$VG_SKIP" ]; then
    note "VG $VG carries the skip-activation flag while LVM is in the temporary state: a reboot leaves the pool offline."
    return 0
  fi
  warn "The skip-activation flag could not be set on $VG. Do NOT reboot the NAS before step 4) Repair has finished:"
  note "QTS would start the pool read-write on the working copy."
  return 1
}

copy_up() { # 0 = the pool is up on the working copy and not through the test (the test activates a flagged VG)
  lvm_check
  [ -z "$VG_SKIP" ] && is_swapped && pool_is_online
}

copy_live() { # 0 = the pool ran on the working copy, which now holds the live metadata; kept in the session state
  if [ "$COPY_LIVE" = 1 ]; then return 0; fi
  copy_up || return 1
  COPY_LIVE=1
  save_state
  logf "COPY_LIVE: pool active on ${TMPLV}_tmeta without the skip-activation flag"
  return 0
}

copy_live_note() { # the plain words for it and the way on
  if is_swapped && pool_is_online; then
    warn "Pool $VG/$POOL is RUNNING read-write on the working copy (${TMPLV}_tmeta), as after a reboot in the temporary state."
    note "It has taken writes since the swap: the working copy now holds the live metadata and the original $META is out of date. Do NOT undo the swap - those writes would be lost and data blocks used twice."
    note "Next: step 2) Prepare takes the pool offline and leaves the swap in place, then step 4) Repair tests the copy and writes it to $META."
  else
    warn "Pool $VG/$POOL ran read-write on the working copy ($TMPLV) and took writes there."
    note "The working copy holds the live metadata and the original $META is out of date. Do NOT go back to the original - those writes would be lost and data blocks used twice."
    note "Next: step 4) Repair tests the copy and writes it to $META."
  fi
}

activation_hints() { # $1 = output of vgchange/lvchange -ay; a hint for each known LVM message
  if grep -qi 'partial LV' "$1" 2>/dev/null; then
    say "  -> 'Refusing activation of partial LV': a PV is in missing mode - 6) Tools -> i)."
  fi
  if grep -qi 'transaction_id' "$1" 2>/dev/null; then
    say "  -> transaction_id mismatch (pool superblock vs LVM): the pool's transaction_id in the LVM"
    say "     configuration must be corrected (vgcfgbackup, edit, vgcfgrestore --force) - KB 'transaction id mismatch'."
  fi
  if grep -qiE 'Check of (thin )?pool' "$1" 2>/dev/null; then
    say "  -> 'Check of thin pool ... failed': pool metadata - step 1) Diagnosis."
  fi
  if grep -qi 'Invalid argument' "$1" 2>/dev/null; then
    say "  -> 'reload ioctl ... Invalid argument': look at the kernel message that came with it:"
    dmesg 2>/dev/null | grep -iE 'too small for target|device-mapper: table' | tail -n 3
    say "     'mdN/drbdN too small for target' = the RAID group is smaller than the LVs on it. Compare"
    say "     mdadm -D /dev/mdN (Array Size) with lvdisplay --map --unit S; that is a RAID-layer repair."
  fi
}

same_file() {
  if have cmp; then
    cmp -s "$1" "$2"
    return $?
  fi
  [ "$(awk 'NR==FNR {a[FNR]=$0; n=FNR; next} {m=FNR; if (a[FNR] != $0) c++} END {if (n != m) c++; print c+0}' "$1" "$2")" = 0 ]
}

# ==================================================================================================
#  RAID - any level; the md arrays under the PVs of this VG are checked
# ==================================================================================================
raid_check() {
  local __p __mds=""
  for __p in $(pvs --noheadings -o pv_name,vg_name 2>/dev/null | awk -v v="$VG" '$2==v {print $1}'); do
    case "$__p" in
      /dev/md[0-9]*) __mds="$__mds ${__p#/dev/}" ;;
      /dev/drbd[0-9]*) __mds="$__mds md${__p#/dev/drbd}" ;;
    esac
  done
  RAID_SUM=$(awk -v want=" $__mds " '
    function fl(   st) {
      if (nm == "") return
      if (want ~ /^ *$/) { if (nm ~ /^md(9|13|256|321|322)$/) return }
      else if (index(want, " " nm " ") == 0) return
      st = "OK"
      if (act != "active") st = "INACTIVE"
      else if (sy != "") st = "SYNC:" sy
      else if (dg) st = "DEGRADED"
      printf "%s %s %s %s; ", nm, lv, cnt, st
    }
    /^md[0-9]+ *:/ {
      fl(); nm = $1; act = $3; lv = "?"; cnt = ""; dg = 0; sy = ""
      for (i = 3; i <= NF; i++) if ($i ~ /^(raid[0-9]+|linear|multipath)$/) { lv = $i; break }
      next
    }
    nm != "" && match($0, /\[[0-9]+\/[0-9]+\]/) {
      cnt = substr($0, RSTART, RLENGTH)
      split(substr($0, RSTART + 1, RLENGTH - 2), c, "/")
      if (c[1] != c[2]) dg = 1
    }
    nm != "" && match($0, /(recovery|resync|reshape|check) *=/) {
      sy = substr($0, RSTART, RLENGTH); sub(/ *=/, "", sy)
    }
    /^[ \t]*$/ { fl(); nm = "" }
    END { fl() }
  ' "$F_MDSTAT" 2>/dev/null)
  RAID_SUM=${RAID_SUM%; }
  case "$RAID_SUM" in
    "")
      RAID_STATE=unknown
      RAID_SUM="(no md array recognised under $VG)"
      ;;
    *INACTIVE*) RAID_STATE=inactive ;;
    *SYNC:*) RAID_STATE=syncing ;;
    *DEGRADED*) RAID_STATE=degraded ;;
    *) RAID_STATE=ok ;;
  esac
}

_raid_gate() { # before every writing step: the layers under the pool first (hardware, LVM, RAID)
  lvm_gate || return 1
  cache_gate || return 1
  hw_gate || return 1
  if [ "$CACHE_MODE" = unknown ] && [ -z "$CACHE_ACK" ]; then
    if [ -n "$LVM_CACHE" ]; then
      warn "An SSD cache layer sits in this VG (cache_client / fcorig)."
    else
      warn "An SSD cache is configured and its type is not known ($CACHE_SRC)."
    fi
    note "Remove or disable the SSD cache in QTS before a metadata repair whenever that is possible."
    ask_yn "Continue with the cache layer in place?" n || return 1
    CACHE_ACK=1
  fi
  raid_check
  case "$RAID_STATE" in
    ok | unknown) return 0 ;;
    inactive)
      err "RAID: $RAID_SUM"
      note "The array under $VG is inactive - repair the RAID first (storage is repaired bottom-up)."
      return 1
      ;;
    *)
      warn "RAID: $RAID_SUM"
      note "Repairing metadata on a degraded or syncing array raises the risk."
      ask_yn "Continue anyway?" n
      ;;
  esac
}

# ==================================================================================================
#  The device stack above the VG (cachedevN, ce_cachedevN...) and its mount points
# ==================================================================================================
_compute_stack() {
  local __tab __n __ma __mi __op __d __mp __sub __all=""
  __tab=$(dm_list | while IFS=: read -r __n __ma __mi __op; do
    __d=$(dmsetup deps "$__n" 2>/dev/null | sed -e 's/^[^(]*//' -e 's/(\([0-9]*\), *\([0-9]*\))/\1:\2/g')
    printf '%s %s:%s|%s\n' "$__n" "$__ma" "$__mi" "$__d"
  done)
  ST_UPPER=$(printf '%s\n' "$__tab" | awk -v pfx="$VGDM-" '
    NF {
      split($0, h, "|"); split(h[1], a, " ")
      n++; name[n] = a[1]; id[n] = a[2]; deps[n] = h[2]
      if (index(a[1], pfx) == 1) inset[a[2]] = 1; else cand[n] = 1
    }
    END {
      lvl = 0; ch = 1
      while (ch) {
        ch = 0; lvl++
        for (i = 1; i <= n; i++) if (cand[i] && !lv[i]) {
          m = split(deps[i], d, " ")
          for (j = 1; j <= m; j++) if (inset[d[j]]) { lv[i] = lvl; ch = 1; break }
        }
        for (i = 1; i <= n; i++) if (lv[i] == lvl) inset[id[i]] = 1
      }
      for (l = lvl; l >= 1; l--) for (i = 1; i <= n; i++) if (lv[i] == l) print name[i]
    }')
  ST_VGDEVS=$(dm_list | awk -F: -v pfx="$VGDM-" 'index($1,pfx)==1 {print $1}')
  for __n in $ST_UPPER $ST_VGDEVS; do
    for __mp in $(awk -v a="$DEVMAP/$__n" -v b="/dev/mapper/$__n" '$1==a || $1==b {print $2}' "$F_MOUNTS"); do
      __all="$__all $__mp"
    done
  done
  for __mp in $__all; do
    for __sub in $(awk -v p="$__mp/" 'index($2,p)==1 {print $2}' "$F_MOUNTS"); do __all="$__all $__sub"; done
  done
  # shellcheck disable=SC2086
  ST_MPS=$(printf '%s\n' $__all | grep . | sort -ru)
}

_umount_one() { # unmount; when busy, escalate only as far as the operator chooses
  local __pids
  while :; do
    if ! grep -q " $1 " "$F_MOUNTS"; then return 0; fi
    if run umount "$1"; then return 0; fi
    warn "Cannot unmount $1 (busy)."
    if have lsof; then
      lsof "$1" 2>/dev/null | head -n 15
    fi
    say "  [r] retry   [q] stop the snapshot manager   [s] stop all QTS services   [k] kill -9 the holders"
    rd "  [b] flag the VG to stay offline and reboot   [a] abort: "
    case "$ANS" in
      b | B) if skip_and_reboot; then return 1; fi ;;
      q | Q) stop_qsnapman ;;
      s | S) stop_services ;;
      k | K)
        __pids=$(lsof "$1" 2>/dev/null | awk -v me="$$" 'NR>1 && $2 ~ /^[0-9]+$/ && $2 != me {print $2}' | sort -u)
        if [ -n "$__pids" ]; then
          # shellcheck disable=SC2086
          run kill -9 $__pids
          sleep 2
        else
          say "  lsof shows no holders (check: mount, swap, NFS, iSCSI)."
        fi
        ;;
      a | A) return 1 ;;
    esac
  done
}

_stop_qsnapman() { # the snapshot manager holds the snapshot mounts of every pool
  if [ "$QSNAP_STOPPED" = 1 ]; then return 0; fi
  QSNAP_STOPPED=1
  save_state # recorded before the attempt: even a partial stop gets undone in step 5
  if [ -x "$INITD/qsnapman.sh" ]; then
    run_long "$INITD/qsnapman.sh" stop ||
      warn "qsnapman.sh stop returned $RC - the unmount that follows shows whether that matters."
  fi
}

_stop_services() { # the full list of the existing SOP, in its order
  local __failed=""
  SERVICES_STOPPED=1
  QSNAP_STOPPED=1
  save_state # recorded before the first command, see above
  if [ -x "$INITD/services.sh" ]; then run_long "$INITD/services.sh" stop || __failed="$__failed services.sh"; fi
  if [ -x "$INITD/qsnapman.sh" ]; then run_long "$INITD/qsnapman.sh" stop || __failed="$__failed qsnapman.sh"; fi
  if [ -x "$DAEMON_MGR" ]; then run "$DAEMON_MGR" lvmetad stop "/sbin/lvmetad" || __failed="$__failed lvmetad"; fi
  if [ -e /var/run/lvm/lvmetad.socket ]; then run rm -f /var/run/lvm/lvmetad.socket; fi
  if [ -x "$INITD/qulog.sh" ]; then run_long "$INITD/qulog.sh" force-stop || __failed="$__failed qulog.sh"; fi
  if [ -n "$__failed" ]; then
    warn "These stop commands returned an error:$__failed"
    note "QTS init scripts also do that when one of their services was simply not running. The real test is the unmount and deactivation that follow; the services stay flagged as stopped."
  fi
}

_dm_remove() { # remove one device above the LVs (cachedevN, ce_cachedevN); 1 = the operator aborted
  while :; do
    case "$1" in
      ce_*) if have cryptsetup; then run cryptsetup luksClose "$1"; else run dmsetup remove "$1"; fi ;;
      *) run dmsetup remove "$1" ;;
    esac
    if [ "$RC" = 0 ]; then return 0; fi
    warn "Cannot remove $1 (in use)."
    rd "  [r] retry   [s] stop all QTS services and retry   [b] flag the VG to stay offline and reboot   [a] abort: "
    case "$ANS" in
      s | S) stop_services ;;
      b | B) if skip_and_reboot; then return 1; fi ;;
      a | A) return 1 ;;
    esac
  done
}

_do_prepare() {
  local __mp __d __sw __left
  hdr "Prepare: unmount the volumes and deactivate $VG"
  cache_gate || return 1 # before anything is unmounted: removing ce_cachedevN over a dirty write-back cache can lose data
  if is_swapped; then
    say "LVM is in the temporary state (pool -> ${TMPLV}_tmeta): this step takes the pool offline and leaves the swap as it is."
    if copy_live; then note "The working copy holds the live metadata. After this step: 4) Repair, not 6c."; fi
  fi
  compute_stack
  dbg "stack above $VG: upper=[$(echo $ST_UPPER)] mounts=[$(echo $ST_MPS)]"
  if [ -z "$ST_MPS" ] && [ -z "$ST_UPPER" ] && ! pool_is_online; then
    ok "Pool $VG/$POOL is already offline and nothing is mounted."
    clear_skip_flag
    swap_guard
    if ! stage_ge offline; then set_stage offline; fi
    return 0
  fi
  say "Mounted:               $(echo ${ST_MPS:-none})"
  if [ -n "$ST_MPS" ]; then printf '%s\n' $ST_MPS 2>/dev/null >"$LOGDIR/before.mounts"; fi # for the check after the start
  say "Devices above the LVs: $(echo ${ST_UPPER:-none})"
  say "Active LVs in $VG:     $(echo ${ST_VGDEVS:-none})"
  say "How to take the pool offline:"
  PICK_LIST="gentle - unmount only what belongs to this pool; services stop only if something stays busy (other pools keep working)
full   - stop all QTS services first (services, qsnapman, lvmetad, qulog), then unmount; the whole NAS goes quiet"
  pick "Mode" || return 1
  snapshot before-offline
  case "$PICK" in
    full*) stop_services ;;
    *) if printf '%s\n' "$ST_MPS" | grep -q '^/mnt/snapshot/'; then
      say "Snapshots of this pool are mounted - the snapshot manager has to stop (it serves every pool)."
      stop_qsnapman
    fi ;;
  esac
  # swap files on the volumes of this pool only (.swap/qnap_swap); the swap partitions stay on
  for __sw in $(awk 'NR>1 {print $1}' "$F_SWAPS" 2>/dev/null); do
    for __mp in $ST_MPS; do
      case "$__sw" in "$__mp"/*) run swapoff "$__sw" ;; esac
    done
  done
  compute_stack
  for __mp in $ST_MPS; do
    umount_one "$__mp" || {
      err "Stopped - $__mp is still mounted."
      return 1
    }
  done
  for __d in $ST_UPPER; do
    dm_remove "$__d" || {
      err "Stopped - $__d is still there."
      return 1
    }
  done
  while :; do
    run lvchange -an "$VG"
    __left=$(vg_dm_left "$META")
    if [ -n "$__left" ]; then
      run vgchange -an "$VG"
      __left=$(vg_dm_left "$META")
    fi
    if [ -z "$__left" ]; then break; fi
    err "Still active: $(echo $__left)"
    note "Check from another session: dmsetup info -c ; mount ; cat /proc/swaps"
    rd "  [r] retry   [s] stop all QTS services and retry   [b] flag the VG to stay offline and reboot   [a] abort: "
    case "$ANS" in
      b | B) if skip_and_reboot; then return 1; fi ;;
      s | S)
        stop_services
        compute_stack
        for __mp in $ST_MPS; do umount_one "$__mp" || return 1; done
        for __d in $ST_UPPER; do dm_remove "$__d" || return 1; done
        ;;
      a | A) return 1 ;;
    esac
  done
  ok "VG $VG is deactivated."
  swap_guard
  if ! stage_ge offline; then set_stage offline; fi
  return 0
}

# ==================================================================================================
#  Work directory (logs + backup)
# ==================================================================================================
sess_id() { printf '%s' "$STARTED" | tr -cd '0-9'; } # name of the session's log folder on md9; STARTED is in the saved state

# 0 when $PERSIST is on a mounted read-write disk filesystem (md9) with room above the floor; else the reason in PLOG_WHY.
# With md9 not mounted, /mnt/HDA_ROOT is a folder on the RAM disk.
persist_room() {
  local __mb __in
  PLOG_WHY=""
  if ! awk -v p="$PERSIST/" '
    { m = $2; if (m != "/") m = m "/"
     if (index(p, m) == 1 && length(m) >= best) { best = length(m); src = $1; fs = $3; mp = $2; opt = $4 } }
    END { exit !(src ~ /^\/dev\// && src !~ /^\/dev\/ram/ && fs != "tmpfs" && mp != "/" && opt ~ /(^|,)rw(,|$)/) }
  ' "$F_MOUNTS" 2>/dev/null; then
    PLOG_WHY="md9 is not mounted read-write"
    return 1
  fi
  __mb=$(free_mb "$PERSIST")
  # BusyBox 1.24.1 on the test NAS prints plain numbers; the df in QNAP's md9 documents prints 8.1K
  __in=$(df -i "$PERSIST" 2>/dev/null | tail -n 1 | awk '{
    v = $(NF-2); if (v !~ /^[0-9]/) exit
    n = v + 0; if (v ~ /[Kk]$/) n *= 1000; else if (v ~ /M$/) n *= 1000000; else if (v ~ /G$/) n *= 1000000000
    printf "%d", n }')
  if [ -z "$__mb" ] || [ -z "$__in" ]; then
    PLOG_WHY="the free space of md9 cannot be read"
  elif [ "$__mb" -lt "$PLOG_MIN_MB" ]; then
    PLOG_WHY="md9 has only $__mb MiB free"
  elif [ "$__in" -lt "$PLOG_MIN_INODES" ]; then
    PLOG_WHY="md9 has only $__in free inodes"
  fi
  [ -z "$PLOG_WHY" ]
}

logs_home() { # the end of the start: without a work directory the logs go to md9 when it has room, else they stay in /tmp
  local __id __d __x __n=0
  if [ -z "$STARTED" ]; then STARTED=$(ts); fi # a state saved by an old version: the session gets its name now
  __id=$(sess_id)
  # old sessions: the newest $PLOG_KEEP folders stay (the names sort by time), and the one of this session
  ls "$PERSIST/logs" 2>/dev/null | sort -r | while read -r __x; do
    case "$__x" in '' | *[!0-9]*) continue ;; esac
    __n=$((__n + 1))
    if [ "$__n" -gt "$PLOG_KEEP" ] && [ "$__x" != "$__id" ]; then rm -rf "$PERSIST/logs/$__x"; fi
  done
  case "$LOGDIR" in "$TMPD"/*) ;; *) return 0 ;; esac
  __d="$PERSIST/logs/$__id"
  if [ -n "$__id" ] && persist_room; then
    if mkdir -p "$__d" 2>/dev/null && { echo ok >"$__d/.probe"; } 2>/dev/null; then
      rm -f "$__d/.probe"
      switch_logs "$__d"
    else
      rmdir "$__d" "$PERSIST/logs" 2>/dev/null # empty ones only
      PLOG_WHY="md9 cannot be written"
    fi
  fi
  case "$LOGDIR" in
    "$TMPD"/*)
      warn "Logs: $LOGDIR"
      note "They are in the RAM disk, because ${PLOG_WHY:-md9 could not take them}: a reboot loses them."
      ;;
    *)
      say "Logs: $LOGDIR"
      say "They are on md9 and survive a reboot."
      ;;
  esac
  say "Long command output is cut in these logs; a work directory keeps full logs."
}

switch_logs() { # move the logs to a new directory; the session's folder on md9 goes away once all of it is in the new place
  local __new=$1 __old=$LOGDIR __id __m="" __f __bad=""
  mkdir -p "$__new" || return 1
  trace_off
  __id=$(sess_id)
  if [ -n "$__id" ] && [ -d "$PERSIST/logs/$__id" ] && [ "$PERSIST/logs/$__id" != "$__new" ]; then
    __m="$PERSIST/logs/$__id"
    for __f in "$__m"/*; do
      [ -f "$__f" ] || continue
      case "${__f##*/}" in
        session.log | commands.log) # appended, so gone from here at once: a second try must not add the same lines again
          if cat "$__f" >>"$__new/${__f##*/}" 2>/dev/null; then rm -f "$__f"; else __bad=1; fi
          ;;
        cmd.out | view.*) ;;
        *) cp "$__f" "$__new"/ 2>/dev/null || __bad=1 ;;
      esac
    done
    if [ -z "$__bad" ]; then
      rm -rf "$__m"
      rmdir "$PERSIST/logs" 2>/dev/null # when it was the last one
      case "$TC_FILE" in "$__m"/*) TC_FILE="$__new/${TC_FILE##*/}" ;; esac
      case "$ORIG_TC" in "$__m"/*) ORIG_TC="$__new/${ORIG_TC##*/}" ;; esac
      case "$REPORT_FILE" in "$__m"/*) REPORT_FILE="$__new/${REPORT_FILE##*/}" ;; esac
    fi
  fi
  if [ "$__old" != "$__m" ]; then
    __bad=""
    if [ -s "$LOG" ]; then cat "$LOG" >>"$__new/session.log" 2>/dev/null || __bad=1; fi
    if [ -s "$CMDLOG" ]; then cat "$CMDLOG" >>"$__new/commands.log" 2>/dev/null || __bad=1; fi
    cp "$__old"/state-* "$__old"/dmesg-* "$__old"/thin_check-* "$__old"/health-* "$__old"/before.mounts "$__old"/bringup.* "$__old"/*.bringup-* "$__new"/ 2>/dev/null
    # moved, not copied: the next start in /tmp must not carry the same lines over again
    case "$__bad:$__old" in :"$TMPD"/*) rm -f "$LOG" "$CMDLOG" ;; esac
  fi
  LOGDIR=$__new
  LOG="$LOGDIR/session.log"
  CMDLOG="$LOGDIR/commands.log"
  set_cap
  if [ -n "$__m" ] && [ -d "$__m" ]; then
    warn "Some log files could not be copied from $__m to $__new. They stay on md9; the next start of this session with the work directory tries again."
  fi
  if [ -n "$DEBUG" ]; then trace_on; fi
}

_choose_workdir() {
  local __list="" __mp __base __free
  compute_stack
  hdr "Work directory (logs + metadata backup)"
  say "A raw metadata image takes $META_MB MiB; gzip usually makes it many times smaller."
  # real block devices only: external drives and volumes of other pools / static volumes
  for __mp in $(awk -v e="$EXTBASE/" '$1 ~ /^\/dev\// && (index($2,e)==1 || $2 ~ /^\/share\/(CE_)?CACHEDEV[0-9]+_DATA$/) && $4 ~ /(^|,)rw(,|$)/ {print $2}' "$F_MOUNTS" | sort -u); do
    case " $(echo $ST_MPS) " in *" $__mp "*) continue ;; esac
    __free=$(free_mb "$__mp")
    __list="$__list$__mp   (free: ${__free:-?} MiB)
"
  done
  PICK_LIST="${__list}Other path (type it in)
No work directory - diagnosis only (short logs, no backup)"
  pick "Where to save" || return 1
  case "$PICK" in
    Other*)
      rd "Path to an existing directory: "
      __base=$ANS
      ;;
    No*)
      WORKDIR=""
      save_state
      return 0
      ;;
    *) __base=${PICK%%   (*} ;;
  esac
  __base=${__base%/}
  case "$__base" in
    /*) ;;
    *)
      err "Give an absolute path."
      return 1
      ;;
  esac
  case "$__base" in
    *[!A-Za-z0-9_./-]*)
      err "Characters not allowed in the path."
      return 1
      ;;
  esac
  if [ ! -d "$__base" ]; then
    err "Directory $__base does not exist."
    return 1
  fi
  if ! on_data_mount "$__base"; then
    err "$__base is not on a mounted data volume or external disk (RAM disk, tmpfs or a system partition)."
    note "A 64 GB image written there would fill RAM and take the NAS down."
    return 1
  fi
  for __mp in $ST_MPS; do
    case "$__base/" in "$__mp"/*)
      err "$__base is on a volume of the pool being repaired."
      return 1
      ;;
    esac
  done
  WORKDIR="$__base/pool-recovery-${HOST:-nas}-$VG-$POOL-$(date +%Y%m%d-%H%M%S)"
  if ! mkdir -p "$WORKDIR/logs" || ! : >"$WORKDIR/.test"; then
    err "Cannot write to $__base."
    WORKDIR=""
    return 1
  fi
  rm -f "$WORKDIR/.test"
  chmod 700 "$WORKDIR" "$WORKDIR/logs" 2>/dev/null # no effect on NTFS/FAT disks, and no reason to stop
  switch_logs "$WORKDIR/logs"
  save_state
  ok "Work directory (free: $(free_mb "$WORKDIR") MiB):"
  note "$WORKDIR"
}

_need_workdir() {
  if [ -n "$WORKDIR" ] && [ -d "$WORKDIR" ] && on_data_mount "$WORKDIR"; then
    # the disk was away at the start and is back: the logs and the state copy return to it
    if [ "$LOGDIR" != "$WORKDIR/logs" ] && switch_logs "$WORKDIR/logs"; then
      save_state
      ok "Work directory $WORKDIR is available again. Logs: $LOGDIR"
    fi
    return 0
  fi
  if [ -n "$WORKDIR" ]; then warn "Work directory $WORKDIR is unavailable (drive unplugged?)."; fi
  choose_workdir && [ -n "$WORKDIR" ]
}

# ==================================================================================================
#  pdata_tools - pick the version (metadata block size: 8192 or 4096)
# ==================================================================================================
_pick_pdata() {
  local __hx __bs="" __t __list=""
  if [ -n "$PDATA" ] && have "$PDATA"; then return 0; fi
  # as tp_collect.sh does: the metadata_block_size field of the superblock (offset 340)
  if have hexdump; then
    __hx=$(dd if="$METADEV" bs=1 skip=340 count=2 2>/dev/null | hexdump | awk 'NR==1 {print $2}')
    case "$__hx" in
      0010 | 2000) __bs=8192 ;;
      0008 | 1000) __bs=4096 ;;
    esac
  elif have od; then
    __hx=$(dd if="$METADEV" bs=1 skip=340 count=2 2>/dev/null | od -An -tx1 2>/dev/null | tr -d ' \n')
    case "$__hx" in
      1000 | 0020) __bs=8192 ;;
      0800 | 0010) __bs=4096 ;;
    esac
  fi
  if [ -n "$__bs" ]; then
    if have "pdata_tools_$__bs"; then
      PDATA="pdata_tools_$__bs"
    elif [ -x "/sbin/pdata_tools_$__bs" ]; then
      PDATA="/sbin/pdata_tools_$__bs"
    elif have pdata_tools; then
      PDATA=pdata_tools
    fi
    if [ -n "$PDATA" ]; then
      ok "Metadata block $__bs B -> tool: $PDATA"
      save_state
      return 0
    fi
    err "pdata_tools_$__bs is not on this system."
    note "Old firmware (<4.3): wget $URL_PDATA_ALT/pdata_tools_$__bs"
    return 1
  fi
  warn "Could not read the block size from the superblock (damaged superblock?)."
  for __t in pdata_tools_8192 pdata_tools_4096 pdata_tools; do
    if have "$__t"; then
      __list="$__list$__t
"
      if "$__t" thin_check --super-block-only "$METADEV" >/dev/null 2>&1; then
        PDATA=$__t
        ok "The superblock is readable with: $PDATA"
        save_state
        return 0
      fi
    fi
  done
  if [ -z "$__list" ]; then
    err "No pdata_tools on this system."
    return 1
  fi
  say "Pool created on kernel 3.12.6/4.x (most pools) -> 8192; on 3.4.x (QTS 4.1.x) -> 4096."
  PICK_LIST=$__list
  pick "Which tool to use" || return 1
  PDATA=$PICK
  save_state
}

# ==================================================================================================
#  thin_check + classification of its output
#    CLEAN      no errors
#    SPACEMAP   errors only in the "checking space map counts" section
#    MAPPING    errors in the trees (devices/mapping/clone/tiering)
#    SUPERBLOCK superblock errors, or the check never reached the trees
#    UNKNOWN    error exit code without recognised messages / the tool did not start
# ==================================================================================================
_thin_check_run() { # thin_check_run <device> <label> [extra option]
  local __res
  TC_FILE="$LOGDIR/thin_check-$2-$(date +%H%M%S).log"
  RL_SAVE=$TC_FILE
  run_long "$PDATA" thin_check ${3:+"$3"} "$1"
  RL_SAVE=""
  TC_RC=$RC
  __res=$(awk -v rc="$TC_RC" '
    /^[ \t]*$/ { next }
    /^examining superblock/ { sec = "sb"; seen_sb = 1; next }
    /^(examining|checking) / {
      if ($0 ~ /^checking space map counts/) sec = "sm"
      else { sec = "tree"; seen_tree = 1 }
      next
    }
    /valid superblock backup/ { next }
    { if (sec == "") sec = "other"; n[sec]++ }
    END {
      if (!seen_sb) c = "UNKNOWN"
      else if (n["sb"] > 0 || !seen_tree) c = "SUPERBLOCK"
      else if (n["tree"] > 0 || n["other"] > 0) c = "MAPPING"
      else if (n["sm"] > 0) c = "SPACEMAP"
      else if (rc == 0) c = "CLEAN"
      else c = "UNKNOWN"
      printf "%s superblock=%d trees=%d space-map=%d other=%d\n", c, n["sb"], n["tree"], n["sm"], n["other"]
    }' "$TC_FILE" 2>/dev/null)
  TC_CLASS=${__res%% *}
  TC_CLASS=${TC_CLASS:-UNKNOWN}
  TC_INFO=${__res#* }
  dbg "thin_check[$2]: class=$TC_CLASS rc=$TC_RC error lines: $TC_INFO"
}

_read_super() { # read_super <device> -> SB_FLAGS, SB_TRANS (1 when unreadable)
  SB_LINE=$("$PDATA" thin_dump -b "$1" 2>/dev/null | head -n 1)
  SB_FLAGS=$(printf '%s\n' "$SB_LINE" | sed -n 's/.* flags="\([0-9][0-9]*\)".*/\1/p')
  SB_TRANS=$(printf '%s\n' "$SB_LINE" | sed -n 's/.* transaction="\([0-9][0-9]*\)".*/\1/p')
  dbg "superblock $1: flags=${SB_FLAGS:-?} transaction=${SB_TRANS:-?}"
  logf "superblock $1: $SB_LINE"
  [ -n "$SB_FLAGS" ]
}

flag_odd() {
  case "$1" in *[13579]) return 0 ;; esac
  return 1
}

_clear_flag_if_set() { # odd flags = needs_check (the pool starts with read-only metadata)
  if ! read_super "$1"; then
    warn "Could not read the superblock flags from $1 - skipping the needs_check clean-up."
    return 0
  fi
  say "Superblock: flags=$SB_FLAGS transaction=$SB_TRANS"
  if flag_odd "$SB_FLAGS"; then
    say "The flags value is odd (needs_check) - clearing it."
    run "$PDATA" thin_check --clear-needs-check-flag --super-block-only "$1"
    read_super "$1"
    if flag_odd "$SB_FLAGS"; then
      err "The needs_check flag is still set."
      return 1
    fi
    ok "Flag cleared (flags=$SB_FLAGS)."
  fi
  return 0
}

affected_lvs() { # name the LVs behind the "thin device N" lines of the last thin_check (lvs -o thin_id)
  local __ids __id __map __name
  __ids=$(sed -n 's/^ *thin device \([0-9][0-9]*\) .*/\1/p' "$TC_FILE" 2>/dev/null | sort -un)
  if [ -z "$__ids" ]; then return 0; fi
  __map=$(lvs --noheadings -o lv_name,thin_id "$VG" 2>/dev/null)
  if [ -z "$__map" ]; then
    note "Affected thin devices: $(echo $__ids)  (lvs -o+thin_id $VG names them)"
    return 0
  fi
  for __id in $__ids; do
    __name=$(printf '%s\n' "$__map" | awk -v i="$__id" '$2 == i {print $1; exit}')
    note "thin device $__id = ${__name:-not a volume of this VG}"
    case "$__name" in lv[0-9]*) AFFECTED="${AFFECTED:+$AFFECTED }$__name" ;; esac
  done
}

class_desc() {
  case "$1" in
    CLEAN) echo "metadata consistent" ;;
    SPACEMAP) echo "space map counts only" ;;
    MAPPING) echo "mapping tree errors" ;;
    SUPERBLOCK) echo "damaged superblock" ;;
    UNKNOWN) echo "unrecognised result" ;;
    *) echo "not diagnosed" ;;
  esac
}

_do_diag() {
  local __h
  hdr "Status and diagnosis"
  raid_check
  say "RAID under $VG: $RAID_SUM"
  health_check
  run lvs -a "$VG"
  lvm_check
  cache_report
  if is_swapped; then
    if copy_live; then
      warn "LVM is in the temporary state: the pool points at ${TMPLV}_tmeta."
      copy_live_note
    else
      warn "LVM is in the temporary state: the pool points at ${TMPLV}_tmeta (interrupted test mount)."
      note "Finish step 4) Repair, or undo it: 6) Tools -> c."
    fi
    return 1
  fi
  if pool_is_online; then
    __h=$(pool_health)
    warn "The pool is active${__h:+ (health: $__h)} - the full check needs the pool offline (step 2)."
    note "Latest kernel messages about the pool:"
    dmesg 2>/dev/null | grep -iE 'device-mapper|thin|I/O error' | tail -n 12
    if ask_yn "Run a read-only live check now (thin_check --non-exclusive)? The result is preliminary" y; then
      METADEV=$(dev_of "$META")
      if is_blk "$METADEV" && pick_pdata; then
        thin_check_run "$METADEV" live --non-exclusive
        if [ "$TC_CLASS" = UNKNOWN ] && ! grep -qi 'busy' "$TC_FILE"; then
          # QTS older than 4.3.5: thin_check has no --non-exclusive and does not lock the device
          thin_check_run "$METADEV" live
        fi
        say "Preliminary result on the live pool: $TC_CLASS - $(class_desc "$TC_CLASS") ($TC_INFO)."
        note "It does not change the session. The repair needs the pool offline: step 2) Prepare."
        # Qtier shows in the superblock: where the live device lets itself be read, step 2 knows it before it unmounts anything
        if read_super "$METADEV" && [ "$(tiers_used)" -ge 2 ]; then
          TIERS_USED=$(tiers_used)
          save_state
          warn "Qtier is in use on this pool: data sits in $TIERS_USED tiers (the metadata carries the tier maps too)."
          note "This script does not repair a pool with Qtier in use: step 2 and the repair stop and point to QNAP support."
        fi
      fi
    fi
    return 1
  fi
  if ! stage_ge offline; then set_stage offline; fi
  clear_skip_flag
  lvm_gate || return 1
  if [ -n "$LVM_CACHE" ]; then
    warn "LVM holds an SSD cache layer (cache_client / *_fcorig)."
    note "If the pool stopped activating after the update to QTS 5.0.0, that is the known 'fcorig' problem (LVM header edit, separate SOP), not damaged pool metadata. Check the cache type first: lvs -a -o+cachemode,cacheiomode  - with a read-write cache (writeback) escalate."
  fi
  meta_up || return 1
  pick_pdata || return 1
  thin_check_run "$METADEV" original
  if stage_ge tmp_ok; then
    say "Stage: $(stage_desc "$STAGE") - this result is informational and does not change the session: $TC_CLASS"
    return 0
  fi
  if [ "$CLASS" != "$TC_CLASS" ]; then RPATH=""; fi
  CLASS=$TC_CLASS
  ORIG_TC=$TC_FILE
  DIAG_TC=${TC_FILE##*/}
  AFFECTED=""
  TIERS_USED=0
  if read_super "$METADEV"; then
    say "Superblock: flags=$SB_FLAGS transaction=$SB_TRANS"
    TIERS_USED=$(tiers_used)
    if [ "${TIERS_USED:-0}" -ge 2 ]; then
      warn "Qtier is in use on this pool: data sits in $TIERS_USED tiers (the metadata carries the tier maps too)."
      note "This script does not repair a pool with Qtier in use: the repair stops and points to QNAP support."
    fi
  fi
  printf '\n'
  case "$CLASS" in
    CLEAN)
      ok "Diagnosis: the metadata is consistent (thin_check found no errors)."
      if flag_odd "$SB_FLAGS"; then
        note "The needs_check flag is set - the repair is just clearing that flag."
      else
        note "Nothing to repair in the pool metadata. If a volume does not mount, the problem is above (filesystem: e2fsck_64) or below (RAID/LVM)."
      fi
      ;;
    SPACEMAP)
      warn "Diagnosis: space map count mismatches only ($TC_INFO)."
      note "The 'reference counts differ' class of the Ghost snapshot SOP. thin_repair through the scratch LV rebuilds the space maps - no LVM swap and no test mount needed."
      ;;
    MAPPING)
      warn "Diagnosis: errors in the mapping trees ($TC_INFO)."
      note "Full procedure: repair on the scratch LV + read-only test mount."
      note "Ranges reported as 'missing mappings' are dropped by thin_repair: those blocks read as empty afterwards, so run a filesystem check on the affected volumes when it is done."
      affected_lvs
      if grep -q 'keys are out of order' "$TC_FILE"; then
        note "'keys are out of order': QNAP has a pdata_tools build that skips such keys and keeps more mappings (KeyOutOfOrder SOP) - step 4, 'another method' when the copy is built."
      fi
      note "Missing mappings can sometimes be found again in orphan nodes: 6) Tools -> l."
      ;;
    SUPERBLOCK)
      warn "Diagnosis: damaged metadata superblock ($TC_INFO)."
      note "When thin_check lists valid superblock backups: 6) Tools -> m restores the superblock"
      note "from a backup (thin_patch). Otherwise the full procedure may still work - the original is not overwritten before the copy is verified. If both fail, escalate with 6a."
      ;;
    *)
      warn "Diagnosis: unrecognised result (rc=$TC_RC, $TC_INFO)."
      note "Treated like mapping errors - the full, most careful procedure."
      ;;
  esac
  case "$CLASS" in
    MAPPING | SUPERBLOCK | UNKNOWN)
      note "Metadata does not get damaged by itself. Look for the cause as well: a RAM test (MemHound), the SMART data of the disks, the RAID state. thin_repair builds the new metadata in memory."
      ;;
  esac
  if ! stage_ge diagnosed; then set_stage diagnosed; else save_state; fi
  return 0
}

# ==================================================================================================
#  Backup: LVM configuration + metadata image (+ optional XML dump)
# ==================================================================================================
backup_drop_new() { # a new image that failed a check goes; the previous one and BACKUP_FILE stay as they were
  rm -f "$1"
  if [ -n "$BACKUP_FILE" ] && [ -s "$BACKUP_FILE" ]; then note "The previous image is unchanged and remains the backup: $BACKUP_FILE"; fi
}

_do_backup() {
  local __img __dst __old __f __free __bytes __got __kind
  hdr "Backup of the pool metadata"
  require_offline || return 1
  need_workdir || {
    err "The backup needs a work directory."
    return 1
  }
  meta_up || return 1
  pick_pdata || return 1
  rm -f "$WORKDIR/tmeta.raw.new" "$WORKDIR/tmeta.raw.gz.new" # left by a run that was cut off; never a backup
  if [ -n "$BACKUP_FILE" ] && [ -s "$BACKUP_FILE" ]; then
    if stage_ge tmp_ok; then
      err "The repair has started - the existing backup ($BACKUP_FILE) stays as the copy of the original."
      return 1
    fi
    ask_yn "A backup already exists ($BACKUP_FILE). Make it again?" n || return 0
  fi
  snapshot before-backup
  # LVM configuration: the original also goes to the system partition (needed to undo the swap)
  run vgcfgbackup -f "$WORKDIR/vg.lvm.origin" "$VG" || {
    err "vgcfgbackup failed."
    return 1
  }
  mkdir -p "$PERSIST" 2>/dev/null
  cp "$WORKDIR/vg.lvm.origin" "$PERSIST/$VG.lvm.origin" 2>/dev/null ||
    warn "Could not keep a copy of the configuration in $PERSIST (md9 full?)."

  __bytes=$(blockdev --getsize64 "$METADEV" 2>/dev/null)
  if [ -z "$__bytes" ]; then __bytes=$(awk -v m="$META_MB" 'BEGIN {printf "%.0f", m * 1048576}'); fi
  # the new image is written as *.new and takes its final name only after every check below
  __old=$BACKUP_FILE
  __free=$(free_mb "$WORKDIR")
  __free=${__free:-0}
  __kind=raw
  if [ "$__free" -lt $((META_MB + 256)) ]; then
    warn "Not enough room for a raw image: $__free MiB free, $META_MB MiB needed."
    if [ -f "$WORKDIR/tmeta.raw" ] || [ -f "$WORKDIR/tmeta.raw.gz" ] || { [ -n "$__old" ] && [ -f "$__old" ]; }; then
      note "The previous image is kept until the new one is verified, so the room it takes does not count as free."
    fi
    ask_yn "Write a gzip-compressed image instead (slower, usually many times smaller)?" y || return 1
    __kind=gz
  fi
  if [ "$__kind" = raw ]; then
    __img="$WORKDIR/tmeta.raw.new"
    RL_WATCH=$__img
    RL_TOTAL=$META_MB
    run_long dd "if=$METADEV" "of=$__img" bs=4194304
    RL_WATCH=""
    RL_TOTAL=""
    if [ "$RC" != 0 ]; then
      err "dd ended with an error - the backup failed."
      backup_drop_new "$__img"
      return 1
    fi
    run sync
    __got=$(fsize "$__img")
  else
    __img="$WORKDIR/tmeta.raw.gz.new"
    RL_WATCH=$__img
    RL_TOTAL=$META_MB
    RL_READ="$RCF.ddpid"
    rm -f "$RCF.dd" "$RCF.ddpid" # nothing of an earlier run may pass for this one
    run_long dd_gzip "$METADEV" "$__img"
    rm -f "$RCF.ddpid"
    RL_WATCH=""
    RL_TOTAL=""
    RL_READ=""
    if [ "$RC" != 0 ] || [ "$(cat "$RCF.dd" 2>/dev/null)" != 0 ]; then
      err "dd | gzip ended with an error - the backup failed."
      backup_drop_new "$__img"
      return 1
    fi
    run sync
    say "Verifying the archive (full read)..."
    run_long gz_size "$__img"
    __got=$(tail -n 1 "$LOGDIR/cmd.out" | tr -d ' ')
    say "Comparing the archive with the device byte by byte..."
    run_long same_data "$__img" "$METADEV" gz
    if [ "$RC" = 1 ]; then
      err "The archive differs from the device - the backup failed."
      backup_drop_new "$__img"
      return 1
    fi
  fi
  if [ -n "$__bytes" ] && [ "$__got" != "$__bytes" ]; then
    err "The copy ($__got B) differs in size from the device ($__bytes B) - the backup failed."
    backup_drop_new "$__img"
    return 1
  fi
  if [ "$__kind" = raw ]; then
    say "Copy check per the SOP: thin_check of the image must give the same result as the original."
    if [ -z "$ORIG_TC" ] || [ ! -s "$ORIG_TC" ]; then
      thin_check_run "$METADEV" original
      ORIG_TC=$TC_FILE
    fi
    thin_check_run "$__img" image
    if ! same_file "$ORIG_TC" "$TC_FILE"; then
      err "thin_check of the copy differs from the original - the copy is not reliable and was removed."
      backup_drop_new "$__img"
      return 1
    fi
    ok "thin_check of the copy is identical to the original."
  fi
  __dst=${__img%.new}
  run mv -f "$__img" "$__dst" || {
    err "Could not rename the verified image to $__dst - the backup failed."
    backup_drop_new "$__img"
    return 1
  }
  BACKUP_FILE=$__dst
  BACKUP_KIND=$__kind
  NOBACKUP=""
  save_state
  # one image is left: what the previous backup pointed to and a stale image of the other kind go now
  for __f in "$__old" "$WORKDIR/tmeta.raw" "$WORKDIR/tmeta.raw.gz"; do
    if [ -z "$__f" ] || [ "$__f" = "$__dst" ] || [ ! -f "$__f" ]; then continue; fi
    if stage_ge tmp_ok; then
      warn "The repair has started - the older image $__f is kept. The current backup is $__dst."
    elif rm -f "$__f"; then
      say "Removed the previous image: $__f"
    else
      warn "Could not remove the previous image $__f. Remove it by hand: the current backup is $__dst."
    fi
  done
  ok "Metadata copy: $__dst ($__got B)"

  XML_OK=""
  if ask_yn "Also save a full XML dump (thin_dump --repair)? Needed for the legacy path and for analysis" y; then
    run_long "$PDATA" thin_dump "$METADEV" --repair -o "$WORKDIR/thin_dump.xml"
    if [ "$RC" = 0 ] && tail -n 3 "$WORKDIR/thin_dump.xml" 2>/dev/null | grep -q '</superblock>'; then
      XML_OK=1
      ok "XML dump: $WORKDIR/thin_dump.xml ($(fsize "$WORKDIR/thin_dump.xml") B)"
    else
      rm -f "$WORKDIR/thin_dump.xml"
      warn "The XML dump is incomplete (rc=$RC) - removed, it will not be used. The image backup is valid."
    fi
  fi
  if ! stage_ge backed_up; then set_stage backed_up; else save_state; fi
  return 0
}

# ==================================================================================================
#  LVM configuration edit (exactly the two changes of the "Pool recovery" procedure):
#    in the pool section:  metadata = "<meta_from>"  ->  "<meta_to>"
#    LV header:            <lv_from> {               ->  <lv_to> {
# ==================================================================================================
_cfg_edit() { # cfg_edit <in> <out> <meta_from> <meta_to> <lv_from> <lv_to>
  local __diffs
  awk -v pool="$POOL" -v mf="$3" -v mt="$4" -v lf="$5" -v lt="$6" '
    {
      line = $0
      if (!inpool && $1 == pool && $2 == "{") { inpool = 1; depth = 1; print line; next }
      if (!inpool && $1 == lf && $2 == "{" && !ren) {
        i = index(line, lf)
        line = substr(line, 1, i - 1) lt substr(line, i + length(lf))
        ren++; print line; next
      }
      if (inpool) {
        if ($1 == "metadata" && $2 == "=" && $3 == "\"" mf "\"") {
          i = index(line, "\"" mf "\"")
          line = substr(line, 1, i) mt substr(line, i + 1 + length(mf))
          meta++
        } else if ($0 ~ /\{[ \t]*$/) depth++
        else if ($1 == "}") { depth--; if (depth == 0) inpool = 0 }
      }
      print line
    }
    END { exit !(meta == 1 && ren == 1) }
  ' "$1" >"$2" || return 1
  __diffs=$(awk 'NR==FNR {a[FNR]=$0; n=FNR; next} {m=FNR; if (a[FNR] != $0) c++} END {if (n != m) c=-1; print c+0}' "$1" "$2")
  [ "$__diffs" = 2 ]
}

cfg_trans() { # the pool's transaction_id from an LVM configuration file
  awk -v pool="$POOL" '
    !inpool && $1 == pool && $2 == "{" { inpool = 1; depth = 1; next }
    inpool && $1 == "transaction_id" { print $3; exit }
    inpool && $0 ~ /\{[ \t]*$/ { depth++ }
    inpool && $1 == "}" { depth--; if (depth == 0) exit }
  ' "$1"
}

find_origin() { # path of the original LVM configuration
  local __f
  for __f in "$WORKDIR/vg.lvm.origin" "$PERSIST/$VG.lvm.origin"; do
    if [ -s "$__f" ] && grep -q "metadata = \"$META\"" "$__f" && ! grep -q "${TMPLV}_tmeta" "$__f"; then
      printf '%s' "$__f"
      return 0
    fi
  done
  return 1
}

_unswap() { # restore the original LVM configuration (the pool on <pool>_tmeta again)
  local __left __origin
  if grep -q " $TRYMNT " "$F_MOUNTS"; then
    umount_one "$TRYMNT" || {
      err "Free $TRYMNT first (cd out of it, close the other session)."
      return 1
    }
  fi
  if ! is_swapped; then
    ok "The LVM configuration is the original one."
    return 0
  fi
  run lvchange -an "$VG"
  __left=$(vg_dm_left "$META")
  if [ -n "$__left" ]; then
    err "Cannot deactivate: $(echo $__left). Release the devices and retry."
    return 1
  fi
  if ! __origin=$(find_origin); then
    warn "The saved original configuration is missing - rebuilding it by reversing the changes."
    __origin="$LOGDIR/vg.lvm.reversed"
    runq vgcfgbackup -f "$LOGDIR/vg.lvm.current" "$VG"
    if ! cfg_edit "$LOGDIR/vg.lvm.current" "$__origin" "${TMPLV}_tmeta" "$META" "${TMPLV}_tmeta" "$TMPLV"; then
      err "Could not rebuild the configuration. By hand: in a vgcfgbackup file change"
      note "metadata = \"${TMPLV}_tmeta\" -> \"$META\" and the section ${TMPLV}_tmeta -> $TMPLV,"
      note "then: vgcfgrestore $VG -f <file> --force"
      return 1
    fi
  fi
  run vgcfgrestore "$VG" -f "$__origin" --force || {
    err "vgcfgrestore (original) failed."
    return 1
  }
  lvmetad_refresh
  if is_swapped; then
    err "LVM is still in the temporary state."
    return 1
  fi
  ok "Original LVM configuration restored (pool -> $META)."
  clear_skip_flag # the restore took it off already, unless the original was saved with it
  return 0
}

# ==================================================================================================
#  Step A: thin_repair  original -> scratch LV, full check of the result
# ==================================================================================================
find_alt_tool() { # a pdata_tools build put next to the script or into the work directory; prints its path
  local __c
  for __c in "$CWD/pdata_tools" "$WORKDIR/pdata_tools" "$CWD/pdata_tools_8192" "$WORKDIR/pdata_tools_8192" \
    "$CWD/pdata_tools_X86_64" "$CWD/pdata_tools_ARM_64"; do
    if [ -x "$__c" ]; then
      printf '%s' "$__c"
      return 0
    fi
  done
  return 1
}

_make_copy() { # build the working copy on the scratch LV: repair | altdump | xml | llxml
  local __tool __xml
  case "$1" in
    repair)
      RL_CRIT=1
      run_long "$PDATA" thin_repair -i "$METADEV" -o "$TMPDEV"
      RL_CRIT=""
      ;;
    altdump)
      need_workdir || return 1
      say "KeyOutOfOrder SOP: a pdata_tools build that skips out-of-order keys keeps more mappings."
      ask_file "Path to that pdata_tools binary" "$(find_alt_tool)" || return 1
      __tool=$ANS
      if [ ! -x "$__tool" ]; then
        err "$__tool is not executable (chmod +x)."
        return 1
      fi
      say "Binary: $__tool ($(file_digest "$__tool"))"
      __xml="$WORKDIR/thin_dump_alt.xml"
      run_long "$__tool" thin_dump "$METADEV" -o "$__xml"
      if [ "$RC" != 0 ] || ! tail -n 3 "$__xml" 2>/dev/null | grep -q '</superblock>'; then
        err "The dump is incomplete (rc=$RC)."
        RC=1
        return 1
      fi
      RL_CRIT=1
      run_long "$__tool" thin_restore -i "$__xml" -o "$TMPDEV"
      RL_CRIT=""
      ;;
    xml)
      ask_file "Path to the XML dump" "${XML_OK:+$WORKDIR/thin_dump.xml}" || return 1
      __xml=$ANS
      if ! tail -n 3 "$__xml" | grep -q '</superblock>'; then
        err "$__xml does not end with </superblock>."
        RC=1
        return 1
      fi
      RL_CRIT=1
      run_long "$PDATA" thin_restore -i "$__xml" -o "$TMPDEV"
      RL_CRIT=""
      ;;
    llxml)
      ask_file "Path to restore.xml (built from thin_ll_dump, see 6) Tools -> l)" "" || return 1
      __xml=$ANS
      RL_CRIT=1
      run_long "$PDATA" thin_ll_restore -i "$__xml" -E "$METADEV" -o "$TMPDEV"
      RL_CRIT=""
      ;;
  esac
  [ "$RC" = 0 ]
}

_path_tmp() {
  local __lt __how
  if stage_ge tmp_ok; then return 0; fi
  hdr "Step A: thin_repair $META -> $TMPLV (working copy)"
  require_offline || return 1
  raid_gate || return 1
  say "The original metadata is not changed in this step."
  say "The scratch LV $VG/$TMPLV ($(lv_size_mb "$TMPLV") MiB) will be overwritten."
  if [ "$(lv_size_mb "$TMPLV")" -lt "$META_MB" ]; then
    warn "The scratch LV is smaller than the metadata LV ($META_MB MiB)."
    note "That is enough when the used metadata fits. If it does not, thin_repair ends with an error and the original stays untouched."
  fi
  __how=repair
  if [ -n "$AUTO" ]; then
    auto_say "working copy -> thin_repair"
    ANS=""
  else
    rd "  [Enter] thin_repair   [m] another method (other pdata_tools build, XML, thin_ll_restore)   [n] cancel: "
  fi
  case "$ANS" in
    n | N) return 1 ;;
    m | M)
      PICK_LIST="thin_repair  $META -> $TMPLV with $PDATA
alt dump     thin_dump with another pdata_tools build (the 'skip out of order' one) + thin_restore
xml          thin_restore from an XML dump prepared by hand (an edited thin_dump)
ll restore   thin_ll_restore from a restore.xml (orphan nodes, lost device root)"
      pick "How to build the working copy" || return 1
      case "$PICK" in
        alt*) __how=altdump ;;
        xml*) __how=xml ;;
        ll*) __how=llxml ;;
      esac
      ;;
  esac
  meta_up || return 1
  tmp_up || return 1
  if [ "$(dm_open "$VGDM-$(dm_esc "$TMPLV")")" != 0 ] || [ "$(dm_open "$VGDM-$(dm_esc "$META")")" != 0 ]; then
    err "The metadata LV or the scratch LV is in use (open != 0)."
    return 1
  fi
  snapshot before-thin_repair
  if ! make_copy "$__how"; then
    err "Building the working copy failed (rc=$RC). The original is untouched."
    if grep -q 'bad checksum in superblock' "$LOGDIR/cmd.out" 2>/dev/null; then
      note "The tool cannot read the primary superblock. When thin_check lists valid superblock"
      note "backups, 6) Tools -> m restores it from the newest one (thin_patch) and checks again."
      note "Otherwise collect the logs (7) / the tp_collect package (6a) and escalate."
    else
      note "Collect the logs (7) / the tp_collect package (6a) and escalate."
    fi
    return 1
  fi
  thin_check_run "$TMPDEV" copy
  if [ "$TC_CLASS" != CLEAN ]; then
    err "The repaired copy still has errors ($TC_CLASS: $TC_INFO)."
    note "The original is untouched - not continuing. Escalate with the logs."
    return 1
  fi
  ok "Working copy on $TMPLV: thin_check found no errors."
  clear_flag_if_set "$TMPDEV" || return 1
  if [ -s "$WORKDIR/vg.lvm.origin" ] && [ -n "$SB_TRANS" ]; then
    __lt=$(cfg_trans "$WORKDIR/vg.lvm.origin")
    if [ -n "$__lt" ] && [ "$__lt" != "$SB_TRANS" ]; then
      warn "transaction in the superblock ($SB_TRANS) differs from transaction_id in LVM ($__lt)."
      note "LVM may refuse to activate the pool - then the transaction_id in the LVM configuration has to be corrected (vgcfgbackup / vgcfgrestore)."
      ask_yn "Continue anyway?" n || return 1
    else
      ok "transaction_id matches (superblock=$SB_TRANS, LVM=${__lt:-?})."
    fi
  fi
  set_stage tmp_ok
  return 0
}

# ==================================================================================================
#  Step B: temporary metadata swap in LVM + ro,noload test mount
# ==================================================================================================
_test_mount() { # sets TEST_RESULT = ok | bad | skip
  local __vols __vol
  TEST_RESULT=bad
  if grep -q " $TRYMNT " "$F_MOUNTS"; then umount_one "$TRYMNT" || return 1; fi
  lvtab
  # order by the QNAP numbering: lv1-255 data volumes, lv288-543 iSCSI LUNs, snap* snapshots;
  # the volumes thin_check named (AFFECTED) come first
  __vols=$(printf '%s\n' "$LVTAB" | awk -F'|' -v p="$POOL" -v a=" $AFFECTED " '$4==p && $2 ~ /^V/ {
      k = 3; t = ""
      if ($1 ~ /^snap/) { k = 4; t = ", snapshot" }
      else if ($1 ~ /^lv[0-9]+$/) {
        n = substr($1, 3) + 0
        if (n >= 1 && n <= 255) k = 1
        else if (n >= 288 && n <= 543) { k = 2; t = ", iSCSI LUN - usually no ext4" }
      }
      if (index(a, " " $1 " ")) { k = 0; t = t ", named by thin_check" }
      print k " " $1 "   (" int($3) " MiB" t ")"
    }' | sort | cut -d' ' -f2-)
  if [ -z "$__vols" ]; then
    warn "The pool has no thin volumes to test."
    if ask_yn "Skip the test mount?" n; then TEST_RESULT=skip; fi
    return 0
  fi
  while :; do
    if [ "$(printf '%s\n' "$__vols" | grep -c .)" = 1 ]; then
      PICK=$__vols
    else
      say "Volumes in the pool:"
      PICK_LIST=$__vols
      pick "Which volume to mount for the test" || PICK=""
    fi
    __vol=${PICK%% *}
    if [ -n "$__vol" ]; then
      if [ -n "$AUTO" ]; then # the automatic run takes line 1: a volume that was tried goes last, so [o] reaches the next
        __vols=$(printf '%s\n' "$__vols" | awk -v v="$__vol" '$1 != v { print } $1 == v { l = $0 } END { if (l != "") print l }')
      fi
      mkdir -p "$TRYMNT"
      if run mount -t ext4 -o ro,noload "$(dev_of "$__vol")" "$TRYMNT"; then
        run df -h "$TRYMNT"
        run ls_head "$TRYMNT"
        say ""
        say "Volume $__vol is mounted READ-ONLY at $TRYMNT."
        say "Check the files (also from a second SSH session)."
        if [ "$DATA_ACK" = no ]; then
          warn "No separate backup of this data: copy what matters to another disk NOW, before [y]."
          note "After [y] the next step writes the original metadata."
        else
          say "Important data can be copied out now."
        fi
        while :; do
          rd "  [y] data OK, continue   [s] shell in $TRYMNT   [o] other volume   [n] data NOT OK, back out: "
          case "$ANS" in
            y | Y | t | T)
              TEST_RESULT=ok
              break
              ;;
            n | N)
              TEST_RESULT=bad
              break
              ;;
            o | O)
              TEST_RESULT=next
              break
              ;;
            s | S)
              say "Test shell - leave it with: exit"
              (
                trap - INT QUIT TSTP
                umask "$UMASK0"
                cd "$TRYMNT" && PS1='[TEST ro] \w # ' sh -i 2>&1
              )
              ;;
          esac
        done
        umount_one "$TRYMNT" || return 1
        if [ "$TEST_RESULT" != next ]; then return 0; fi
        continue
      fi
      warn "Mounting $__vol failed (block LUN, encrypted volume or damaged filesystem)."
      dmesg 2>/dev/null | tail -n 6
    fi
    rd "  [o] other volume   [s] skip the test (risk)   [b] back out and stop: "
    case "$ANS" in
      s | S)
        say "Skipping the test = writing the metadata without having read any data through it."
        if ask_word SKIP; then
          TEST_RESULT=skip
          return 0
        fi
        ;;
      b | B)
        TEST_RESULT=bad
        return 0
        ;;
    esac
  done
}

_path_swap_test() {
  local __origin __swp __left
  if stage_ge verified; then return 0; fi
  hdr "Step B: read test on the repaired copy (metadata swap in LVM)"
  if ! is_swapped; then
    require_offline || return 1
    need_workdir || return 1
    __origin="$WORKDIR/vg.lvm.origin"
    __swp="$WORKDIR/vg.lvm.swapped"
    if [ ! -s "$__origin" ]; then
      run vgcfgbackup -f "$__origin" "$VG" || return 1
      mkdir -p "$PERSIST" 2>/dev/null
      cp "$__origin" "$PERSIST/$VG.lvm.origin" 2>/dev/null
    fi
    if ! cfg_edit "$__origin" "$__swp" "$META" "${TMPLV}_tmeta" "$TMPLV" "${TMPLV}_tmeta"; then
      err "Could not prepare the configuration (exactly 2 changes were expected in the file)."
      note "Unusual vgcfgbackup layout - inspect $__origin and do the swap by hand."
      return 1
    fi
    say "Changes in the LVM configuration (temporary):"
    if have diff; then
      runq diff "$__origin" "$__swp"
      cat "$LOGDIR/cmd.out"
    fi
    say "The pool will briefly run on the copy from $TMPLV; the original $META stays unchanged."
    note "The VG gets the skip-activation flag first (lvchange -ky $VG): a reboot during the test leaves the pool offline."
    ask_yn "Do the swap (vgcfgrestore --force) and the test mount?" y || return 1
    run lvchange -an "$VG"
    __left=$(vg_dm_left "$META")
    if [ -n "$__left" ]; then
      err "Still active: $(echo $__left)"
      note "Something of $VG is mounted or open - run step 2) Prepare and retry."
      return 1
    fi
    # the flag goes on before the swap and the swapped file is made again from the flagged configuration:
    # vgcfgrestore replaces the whole configuration, flags included, so LVM is never swapped without the flag
    if run lvchange -ky "$VG" && runq vgcfgbackup -f "$__swp.in" "$VG" &&
      cfg_edit "$__swp.in" "$__swp.k" "$META" "${TMPLV}_tmeta" "$TMPLV" "${TMPLV}_tmeta"; then
      mv -f "$__swp.k" "$__swp"
    else
      rm -f "$__swp.in" "$__swp.k"
      warn "The skip-activation flag could not be put into the swapped configuration."
      note "Without it a reboot during the test starts the pool read-write on the working copy."
      if ! ask_yn "Do the swap without the flag?" n; then
        clear_skip_flag
        return 1
      fi
    fi
    rm -f "$__swp.in"
    run vgcfgrestore "$VG" -f "$__swp" --force || {
      err "vgcfgrestore failed."
      clear_skip_flag
      return 1
    }
    lvmetad_refresh
    if ! is_swapped; then
      err "The swap did not take effect (no ${TMPLV}_tmeta)."
      clear_skip_flag
      return 1
    fi
    set_stage swapped
  else
    warn "Resuming: LVM is already in the temporary state (pool -> ${TMPLV}_tmeta)."
    if ! stage_ge swapped; then set_stage swapped; fi
  fi
  swap_guard
  # a flagged VG activates only with -K (--ignoreactivationskip)
  if [ -n "$VG_SKIP" ]; then run lvchange -ay -K "$VG"; else run lvchange -ay "$VG"; fi
  cp "$LOGDIR/cmd.out" "$LOGDIR/activate.out" 2>/dev/null
  run lvs -a "$VG"
  if ! pool_is_online; then
    err "The pool did not activate on the working copy."
    activation_hints "$LOGDIR/activate.out"
    dmesg 2>/dev/null | tail -n 8
    TEST_RESULT=bad
  else
    snapshot test-mount
    test_mount || {
      err "Test interrupted - LVM stays in the temporary state. Run step 4 again or 6c."
      return 1
    }
  fi
  if [ "$COPY_LIVE" = 1 ] && [ "$TEST_RESULT" != ok ] && [ "$TEST_RESULT" != skip ]; then
    # no way back from here: the original knows nothing of the writes the pool took on the copy
    run lvchange -an "$VG"
    err "Test not passed. Nothing was written; LVM stays in the temporary state and the pool offline."
    note "The working copy on ${TMPLV}_tmeta holds the live metadata, so the swap is not undone and the copy is not built again from the out-of-date original. Escalate with the logs (7) / tp_collect (6a)."
    return 1
  fi
  say "Restoring the original LVM configuration..."
  unswap || {
    err "LVM stays in the temporary state! Retry: 6) Tools -> c."
    return 1
  }
  if [ "$COPY_LIVE" = 1 ]; then
    warn "Do NOT reboot the NAS before step C has written the copy to $META:"
    note "QTS would start the pool on the out-of-date original."
  fi
  case "$TEST_RESULT" in
    ok)
      ok "Data confirmed by the operator."
      set_stage verified
      return 0
      ;;
    skip)
      warn "Test mount skipped at the operator's request."
      set_stage verified
      return 0
      ;;
    *)
      warn "Test not passed - the original metadata was not changed."
      note "The copy on $TMPLV is not usable. Escalate with the logs (7) / tp_collect (6a)."
      RPATH=""
      set_stage backed_up
      return 1
      ;;
  esac
}

# ==================================================================================================
#  Step C: write the repaired metadata to the original tmeta
# ==================================================================================================
backup_verify() { # the image must be there, complete, and exactly as large as the metadata device
  local __want
  if [ -z "$BACKUP_FILE" ] || [ ! -s "$BACKUP_FILE" ]; then return 1; fi
  if [ "$BACKUP_KIND" = gz ]; then
    run_long gzip -t "$BACKUP_FILE"
    return $?
  fi
  __want=$(blockdev --getsize64 "$METADEV" 2>/dev/null)
  [ -z "$__want" ] || [ "$(fsize "$BACKUP_FILE")" = "$__want" ]
}

# backup_gate [staged]: no write to the original metadata without a verified image of it.
# The paths that write straight to the original (legacy, rebuild, superblock) have no way around it.
# The staged path keeps a verified copy on the scratch LV, so it alone has an emergency override,
# and only when the script was started with --allow-no-backup.
_backup_gate() {
  if [ -n "$BACKUP_FILE" ] && [ -s "$BACKUP_FILE" ]; then
    if backup_verify; then return 0; fi
    err "The metadata image $BACKUP_FILE failed its check (size or archive test)."
    note "Make a new one: step 3) Backup."
    return 1
  fi
  if [ "$1" = staged ] && [ "$NOBACKUP" = 1 ] && [ -n "$ALLOW_NO_BACKUP" ]; then return 0; fi
  err "There is no image of the original metadata - this write is refused. Run step 3) Backup."
  if [ "$1" != staged ]; then
    note "This path writes straight to the original; it never runs without the image."
    return 1
  fi
  if [ -z "$ALLOW_NO_BACKUP" ] || [ -n "$AUTO" ]; then
    note "Emergency only, staged path only, never in the automatic run: --allow-no-backup"
    return 1
  fi
  warn "--allow-no-backup: going on WITHOUT an image of the original metadata."
  note "The verified copy stays on $TMPLV, but the damaged original is gone after the write:"
  note "nobody can go back to it, and an escalation to QNAP has nothing left to analyse."
  ask_word NO-BACKUP || return 1
  say "Second confirmation - the name of the pool:"
  ask_word "$VG/$POOL" || return 1
  NOBACKUP=1
  save_state
  return 0
}

_path_commit() {
  if stage_ge final_ok; then return 0; fi
  hdr "Step C: write the repaired metadata $TMPLV -> $META"
  require_offline || return 1
  raid_gate || return 1
  meta_up || return 1
  tmp_up || return 1
  if [ "$(dm_open "$VGDM-$(dm_esc "$TMPLV")")" != 0 ] || [ "$(dm_open "$VGDM-$(dm_esc "$META")")" != 0 ]; then
    err "The metadata LV or the scratch LV is in use (open != 0)."
    return 1
  fi
  say "Checking the working copy once more before the write:"
  thin_check_run "$TMPDEV" copy-precommit
  if [ "$TC_CLASS" != CLEAN ]; then
    err "The working copy on $TMPLV is not clean ($TC_CLASS) - not writing."
    return 1
  fi
  backup_gate staged || return 1
  printf '\n'
  warn "This is the only step that OVERWRITES the original pool metadata ($VG/$META)."
  note "Copy of the original: ${BACKUP_FILE:-NONE}"
  note "Do not interrupt, reboot or power off the NAS until it has finished."
  ask_word YES || return 1
  snapshot before-commit
  set_stage final_started
  run sync
  RL_CRIT=1
  run_long "$PDATA" thin_repair -i "$TMPDEV" -o "$METADEV"
  RL_CRIT=""
  if [ "$RC" != 0 ]; then
    err "thin_repair to $META ended with an error (rc=$RC)."
    note "The good copy is still on $TMPLV - run step 4 again. Copy of the original: ${BACKUP_FILE:-none}."
    return 1
  fi
  thin_check_run "$METADEV" final
  if [ "$TC_CLASS" != CLEAN ]; then
    err "After the write thin_check reports errors ($TC_CLASS: $TC_INFO)."
    note "The working copy on $TMPLV is good - run step 4 again or restore the backup (6d)."
    return 1
  fi
  clear_flag_if_set "$METADEV" || return 1
  run sync
  ok "Original metadata repaired: thin_check found no errors."
  COPY_LIVE="" # the original is the live metadata again
  set_stage final_ok
  return 0
}

# ==================================================================================================
#  Legacy path: thin_dump --repair + thin_restore straight to tmeta
# ==================================================================================================
_path_legacy() {
  local __xml
  if stage_ge final_ok; then return 0; fi
  hdr "Legacy path: thin_dump --repair + thin_restore -> $META"
  require_offline || return 1
  raid_gate || return 1
  need_workdir || return 1
  __xml="$WORKDIR/thin_dump.xml"
  meta_up || return 1
  if [ "$STAGE" = final_started ]; then
    if [ "$XML_OK" != 1 ] || [ ! -s "$__xml" ]; then
      err "The write was interrupted and the XML dump is missing - restore the metadata from the backup (6d)."
      return 1
    fi
    warn "Resuming the interrupted thin_restore from the saved dump $__xml."
  elif [ "$XML_OK" != 1 ] || [ ! -s "$__xml" ]; then
    run_long "$PDATA" thin_dump "$METADEV" --repair -o "$__xml"
    if [ "$RC" != 0 ] || ! tail -n 3 "$__xml" 2>/dev/null | grep -q '</superblock>'; then
      err "The XML dump is incomplete (rc=$RC) - not running thin_restore."
      return 1
    fi
    XML_OK=1
    save_state
  fi
  backup_gate || return 1
  printf '\n'
  warn "thin_restore OVERWRITES the original metadata without a prior test on a copy."
  note "Dump: $__xml ($(fsize "$__xml") B). Copy of the original: ${BACKUP_FILE:-NONE}"
  note "Do not interrupt, reboot or power off the NAS until it has finished."
  ask_word YES || return 1
  snapshot before-thin_restore
  set_stage final_started
  RL_CRIT=1
  run_long "$PDATA" thin_restore -i "$__xml" -o "$METADEV"
  RL_CRIT=""
  if [ "$RC" != 0 ]; then
    err "thin_restore ended with an error (rc=$RC). Run step 4 again or restore the backup (6d)."
    return 1
  fi
  thin_check_run "$METADEV" final
  if [ "$TC_CLASS" != CLEAN ]; then
    err "Errors remain after thin_restore ($TC_CLASS: $TC_INFO). Restore the backup (6d) and use the full path."
    return 1
  fi
  clear_flag_if_set "$METADEV" || return 1
  run sync
  ok "Metadata rebuilt: thin_check found no errors."
  set_stage final_ok
  return 0
}

# ==================================================================================================
#  Ghost snapshot SOP: thin_rebuild in place ("reference counts differ"), with QNAP's special build
# ==================================================================================================
_path_rebuild() {
  local __tool
  if stage_ge final_ok; then return 0; fi
  hdr "Ghost snapshot SOP: thin_rebuild in place on $META"
  require_offline || return 1
  raid_gate || return 1
  meta_up || return 1
  say "Needs the pdata_tools build that has thin_rebuild (QTS >= 4.3.5, 8192-byte metadata blocks):"
  note "wget $URL_PDATA_ALT/pdata_tools_X86_64.zip   (ARM: pdata_tools_ARM_64.zip)"
  note "unzip it, rename the binary to pdata_tools, chmod +x, put it next to this script"
  case "$PDATA" in
    *4096*)
      err "This pool uses 4096-byte metadata blocks - the SOP sends that case to the sustain team."
      return 1
      ;;
  esac
  ask_file "Path to that pdata_tools binary" "$(find_alt_tool)" || return 1
  __tool=$ANS
  if [ ! -x "$__tool" ]; then
    err "$__tool is not executable (chmod +x)."
    return 1
  fi
  say "Binary: $__tool ($(file_digest "$__tool"))"
  backup_gate || return 1
  printf '\n'
  warn "thin_rebuild REWRITES the original pool metadata in place ($VG/$META)."
  note "Copy of the original: ${BACKUP_FILE:-NONE}"
  note "It can run for minutes or hours. Do not interrupt, reboot or power off the NAS."
  ask_word YES || return 1
  snapshot before-thin_rebuild
  set_stage final_started
  RL_CRIT=1
  run_long "$__tool" thin_rebuild "$METADEV"
  RL_CRIT=""
  if [ "$RC" != 0 ]; then
    err "thin_rebuild ended with an error (rc=$RC). Restore the backup (6d) or escalate."
    return 1
  fi
  thin_check_run "$METADEV" final
  if [ "$TC_CLASS" != CLEAN ]; then
    err "thin_check still reports errors after thin_rebuild ($TC_CLASS: $TC_INFO)."
    note "The SOP sends this case to the sustain team. The backup can be restored with 6d."
    return 1
  fi
  clear_flag_if_set "$METADEV" || return 1
  run sync
  ok "Metadata rebuilt in place: thin_check found no errors."
  set_stage final_ok
  return 0
}

_path_flag() { # clean metadata, only needs_check
  hdr "Clearing the needs_check flag"
  require_offline || return 1
  meta_up || return 1
  clear_flag_if_set "$METADEV" || return 1
  set_stage final_ok
  return 0
}

# ==================================================================================================
#  Repair: choose the path and walk through its steps
# ==================================================================================================
_choose_path() {
  local __has_tmp="" __sb=""
  if [ -n "$TMPLV" ] && lv_exists "$TMPLV"; then __has_tmp=1; fi
  if [ "$CLASS" = SUPERBLOCK ] && [ -n "$DIAG_TC" ] &&
    grep -q 'valid superblock backups, last backup_id=[0-9]* blocknr=[0-9]' "$LOGDIR/$DIAG_TC" 2>/dev/null; then
    __sb=1
  fi
  case "$CLASS" in
    CLEAN)
      if read_super "$METADEV" && flag_odd "$SB_FLAGS"; then
        say "Clean metadata with the needs_check flag set -> clearing the flag."
        RPATH=flag
        save_state
        return 0
      fi
      ok "The metadata is clean and needs_check is not set - nothing to repair."
      note "Go to 5) Bring the pool up."
      return 1
      ;;
    SPACEMAP)
      say "Diagnosis: space map counts only. Available paths:"
      PICK_LIST=""
      if [ -n "$__has_tmp" ]; then
        PICK_LIST="quick  - thin_repair through $TMPLV, no LVM swap and no test mount (recommended)
full   - the same plus a read-only test mount on the copy (Pool recovery procedure)
"
      fi
      PICK_LIST="${PICK_LIST}legacy - thin_dump --repair + thin_restore straight to $META (old SOP)
rebuild - thin_rebuild in place with QNAP's special pdata_tools build (Ghost snapshot SOP)"
      pick "Repair path" || return 1
      ;;
    *)
      if [ -n "$__sb" ]; then
        # thin_repair cannot read a broken primary superblock; thin_patch puts a valid backup of it back
        say "Diagnosis: damaged superblock, and thin_check lists valid backups of it. Available paths:"
        PICK_LIST="superblock - restore it from the newest valid backup (thin_patch), then check"
        if [ -n "$__has_tmp" ]; then
          PICK_LIST="$PICK_LIST
full       - thin_repair on a copy + test mount"
        else
          PICK_LIST="$PICK_LIST
legacy     - thin_dump --repair + thin_restore straight to $META (old SOP, no scratch LV)"
        fi
        pick "Repair path" || return 1
        case "$PICK" in legacy*) ask_word LEGACY || return 1 ;; esac
      elif [ -n "$__has_tmp" ]; then
        say "Diagnosis: $(class_desc "$CLASS") -> full procedure with the test mount."
        PICK="full"
      else
        warn "No scratch LV - the full procedure (repair on a copy + test) is not possible."
        note "Only the legacy path is left (writes straight to $META) - risky with mapping errors."
        ask_word LEGACY || return 1
        PICK="legacy"
      fi
      ;;
  esac
  case "$PICK" in
    quick*) RPATH=quick ;;
    full*) RPATH=full ;;
    legacy*) RPATH=legacy ;;
    rebuild*) RPATH=rebuild ;;
    superblock*) RPATH=superblock ;;
    *) return 1 ;;
  esac
  save_state
  return 0
}

data_backup_note() { # asked once per session and recorded; it informs, it does not block
  if [ -n "$DATA_ACK" ]; then return 0; fi
  warn "The metadata image protects the pool metadata only. It is not a backup of the files."
  if ask_yn "Is there a separate, restorable backup of the important data on this pool?" n; then
    DATA_ACK=yes
  else
    DATA_ACK=no
    if [ "$RPATH" = quick ]; then
      note "The quick path has no read test, and step C overwrites the original metadata."
      note "Copy what matters to another disk before that. The full path has a read-only test mount for it (step B)."
      if ask_yn "Take the full path instead of the quick one?" n; then RPATH=full; fi
    else
      note "Then the read-only test mount (step B of the full path) is the moment to copy what matters to another disk - before the write in step C, while the original is untouched."
    fi
  fi
  save_state
}

_do_repair() {
  if [ "$STAGE" = "done" ] || [ "$STAGE" = final_ok ]; then
    ok "The metadata repair is already finished. Go to 5) Bring the pool up."
    return 0
  fi
  cache_gate || return 1
  if is_swapped; then
    if copy_live && pool_is_online; then
      err "The repair needs the pool offline."
      copy_live_note
      return 1
    fi
    RPATH=full
    path_swap_test && path_commit
    return $?
  fi
  if [ -z "$CLASS" ]; then
    say "No diagnosis yet - running it first."
    do_diag || return 1
    cache_gate || return 1 # Qtier is known only now
  fi
  require_offline || return 1
  meta_up || return 1
  pick_pdata || return 1
  if [ -z "$RPATH" ]; then choose_path || return 1; fi
  if [ "$RPATH" != flag ] && { [ -z "$BACKUP_FILE" ] || [ ! -s "$BACKUP_FILE" ]; } && [ "$NOBACKUP" != 1 ]; then
    say "A metadata backup is required before the repair - making it now."
    if ! do_backup; then
      case "$RPATH" in
        full | quick) backup_gate staged || return 1 ;;
        *)
          err "No backup - the repair stops here."
          return 1
          ;;
      esac
    fi
  fi
  if [ "$RPATH" != flag ] && [ "$RPATH" != superblock ]; then data_backup_note; fi
  case "$RPATH" in
    full) path_tmp && path_swap_test && path_commit ;;
    quick) path_tmp && path_commit ;;
    legacy) path_legacy ;;
    rebuild) path_rebuild ;;
    flag) path_flag ;;
    superblock) raid_gate && tool_sbrestore ;;
    *)
      err "Unknown path: $RPATH"
      return 1
      ;;
  esac
}

# ==================================================================================================
#  Bring the pool and the volumes up
# ==================================================================================================
pack_logs() {
  local __f __x __list=""
  if [ -z "$WORKDIR" ] || [ ! -d "$WORKDIR" ]; then
    say "Logs: $LOGDIR"
    return 0
  fi
  __f="$WORKDIR/logs-$(date +%Y%m%d-%H%M%S).tgz"
  for __x in logs state report.txt vg.lvm.origin vg.lvm.swapped; do
    if [ -e "$WORKDIR/$__x" ]; then __list="$__list $__x"; fi
  done
  if (cd "$WORKDIR" && tar -czf "$__f" $__list 2>/dev/null); then
    ok "Log package: $__f"
    note "Look through it before sending: it holds the host name, the device layout, directory listings of the test mount and, in debug mode, the shell trace. The metadata image is not in it."
  else
    say "Logs: $LOGDIR"
  fi
}

iscsi_conf_check() { # Recover NAS SOP: init_lvm.sh can reset LUNSectorSize to 0 in iscsi_trgt.conf
  local __f="$CONFD/iscsi_trgt.conf"
  case "$1" in
    save)
      rm -f "$LOGDIR/iscsi-sector.before"
      if [ -r "$__f" ]; then
        grep 'LUNSectorSize' "$__f" 2>/dev/null >"$LOGDIR/iscsi-sector.before"
        cp "$__f" "$LOGDIR/iscsi_trgt.conf.before" 2>/dev/null
      fi
      ;;
    compare)
      if [ ! -s "$LOGDIR/iscsi-sector.before" ]; then return 0; fi
      grep 'LUNSectorSize' "$__f" 2>/dev/null >"$LOGDIR/iscsi-sector.after"
      if ! same_file "$LOGDIR/iscsi-sector.before" "$LOGDIR/iscsi-sector.after"; then
        warn "LUNSectorSize changed in $__f while init_lvm.sh ran (it must not become 0)."
        note "Fix it per LUN: setcfg LUN<n>Info LUNSectorSize <512|4096> -f $__f"
        note "The file from before: $LOGDIR/iscsi_trgt.conf.before"
      fi
      ;;
  esac
}

lvm_conf_check() { # init_lvm.sh moves these files to *.initlvm and builds new ones; a second run overwrites those copies
  local __c __n __b __a __sb __sa
  case "$1" in
    save)
      INITLVM_TAG="before-init_lvm-$(date +%H%M%S)"
      __n=""
      for __c in qlvm.conf raid.conf ssdcache.conf qdrbd.conf; do
        if [ -f "$CONFD/$__c" ] && cp "$CONFD/$__c" "$LOGDIR/$__c.$INITLVM_TAG" 2>/dev/null; then __n="$__n $__c"; fi
      done
      warn "init_lvm.sh rebuilds QTS's volume configuration: volume settings such as alert thresholds can be lost."
      if [ -n "$__n" ]; then
        note "Copies of$__n: $LOGDIR/<name>.$INITLVM_TAG"
      else
        note "No copy was made: none of the configuration files could be copied from $CONFD."
      fi
      ;;
    compare)
      __c="$LOGDIR/qlvm.conf.$INITLVM_TAG"
      if [ -z "$INITLVM_TAG" ] || [ ! -s "$__c" ] || same_file "$__c" "$CONFD/qlvm.conf"; then return 0; fi
      __b=$(grep -c '^threshold *= *[1-9]' "$__c" 2>/dev/null)
      __a=$(grep -c '^threshold *= *[1-9]' "$CONFD/qlvm.conf" 2>/dev/null)
      __sb=$(grep '^\[' "$__c" 2>/dev/null)
      __sa=$(grep '^\[' "$CONFD/qlvm.conf" 2>/dev/null)
      warn "init_lvm.sh changed $CONFD/qlvm.conf (QTS's volume configuration)."
      if [ "${__a:-0}" -lt "${__b:-0}" ]; then
        note "Alert thresholds were lost: $__b value(s) set before, ${__a:-0} now. Set them again in Storage & Snapshots."
      fi
      if [ "$__sa" != "$__sb" ]; then
        note "The list of sections differs ($(printf '%s\n' "$__sb" | grep -c .) before, $(printf '%s\n' "$__sa" | grep -c .) now): the volume IDs may have changed."
      fi
      note "Nothing is restored automatically. The files from before: $LOGDIR/<name>.$INITLVM_TAG"
      ;;
  esac
}

# ==================================================================================================
#  The bring-up through QTS (step 5; the owner's decision of 2026-11-20)
#    storage_util --sys_startup_p2 does all the data work (docs/storage_util-startup.md): it builds cachedevN
#    and mounts the volumes from QTS's storage configuration as it is. Its exit code says little, so the state
#    after it is compared with a table saved before it. init_lvm.sh rebuilds that configuration from the disks
#    (volume IDs handed out anew, alert thresholds 0 %): only as the operator's decision, behind a typed word.
#    Written here: copies and the table in the log directory, nothing else.
# ==================================================================================================
cfg_val() { # cfg_val FILE SECTION KEY: the value of "key = value" inside that one section; nothing when absent
  awk -v s="[$2]" -v k="$3" '
    /^[ \t]*\[/ { t = $0; gsub(/^[ \t]+|[ \t\r]+$/, "", t); on = (t == s); next }
    on {
      p = index($0, "="); if (!p) next
      n = substr($0, 1, p - 1); gsub(/[ \t]/, "", n)
      if (n == k) { v = substr($0, p + 1); gsub(/^[ \t]+|[ \t\r]+$/, "", v); print v; exit }
    }' "$1" 2>/dev/null
}

vol_rows() { # vol_rows FILE: the [VOL_n] sections as lv<baseId>|volId|volName|cachedevN|volType|encryption|readOnly
  awk '
    function f(x) { return (x == "" ? "-" : x) }
    function out() { if (b != "") printf "lv%s|%s|%s|%s|%s|%s|%s\n", b, f(id), f(nm), f(cd), f(ty), f(en), f(ro) }
    /^[ \t]*\[/ { out(); b = id = nm = cd = ty = en = ro = ""; on = ($0 ~ /^[ \t]*\[VOL_[0-9]+\]/); next }
    on {
      p = index($0, "="); if (!p) next
      k = substr($0, 1, p - 1); gsub(/[ \t]/, "", k)
      v = substr($0, p + 1); gsub(/^[ \t]+|[ \t\r]+$/, "", v); gsub(/\|/, "_", v)
      if (k == "baseId") b = v
      else if (k == "volId") id = v
      else if (k == "volName") nm = v
      else if (k == "mappingName") { sub(/^.*\//, "", v); sub(/^ce_/, "", v); cd = v }
      else if (k == "volType") ty = v
      else if (k == "encryption") en = v
      else if (k == "readOnly") ro = v
    }
    END { out() }' "$1" 2>/dev/null
}

vol_mount() { # vol_mount cachedevN: "mount point|options" of the volume on it, or on its unlocked ce_cachedevN
  awk -v a="$1" '{ d = $1; sub(/.*\//, "", d); if (d == a || d == "ce_" a) { print $2 "|" $4; exit } }' "$F_MOUNTS" 2>/dev/null
}

lv_threshold() { # lv_threshold <LV number>: its alert threshold in qlvm.conf, "-" when the file has none
  local __v
  __v=$(cfg_val "$CONFL/qlvm.conf" "LV_$1" threshold)
  echo "${__v:--}"
}

pool_threshold() { # the alert threshold of this pool: section [POOL_n] with poolName = <VG>; "-" when none
  local __s __v=""
  for __s in $(sed -n 's/^ *\[\(POOL_[0-9]*\)\].*/\1/p' "$CONFL/qlvm.conf" 2>/dev/null); do
    if [ "$(cfg_val "$CONFL/qlvm.conf" "$__s" poolName)" = "$VG" ]; then
      __v=$(cfg_val "$CONFL/qlvm.conf" "$__s" threshold)
      break
    fi
  done
  echo "${__v:--}"
}

th_chg() { # th_chg <saved> <now>: the words for an alert threshold that changed
  if [ "$1" = - ]; then
    echo "alert threshold: none saved, $2 % now"
  elif [ "$2" = - ]; then
    echo "alert threshold $1 % -> gone from qlvm.conf, set $1 % again"
  else
    echo "alert threshold $1 % -> $2 %, set $1 % again"
  fi
}

# The expected table. Written once per session: after the first scan QTS's volume table is the product of
# that scan, and a table made from it would agree with whatever the scan left out.
bringup_table() {
  local __t="$LOGDIR/bringup.expected" __lv __id __nm __cd __ty __en __ro __m __n
  if [ -s "$__t" ]; then return 0; fi
  lvtab
  {
    printf '# %s, %s/%s before the bring-up; from %s and %s\n' "$(ts)" "$VG" "$POOL" "$F_VOLCONF" "$CONFL/qlvm.conf"
    printf '# lv|volId|volName|cachedevN|volType|encryption|readOnly|alert threshold|mount point\n'
    vol_rows "$F_VOLCONF" | while IFS='|' read -r __lv __id __nm __cd __ty __en __ro; do
      if [ "$(lv_field "$__lv" 4)" != "$POOL" ]; then continue; fi
      case "$(lv_field "$__lv" 2)" in V*) ;; *) continue ;; esac
      __m=$(vol_mount "$__cd")
      __m=${__m%%|*}
      if [ -z "$__m" ]; then
        __m="-"
        if [ "$__ty" = 1 ] && [ "$__en" = yes ]; then
          __m="/share/CE_CACHEDEV${__cd#cachedev}_DATA"
        elif [ "$__ty" = 1 ]; then
          __m="/share/CACHEDEV${__cd#cachedev}_DATA"
        fi
      fi
      printf '%s|%s|%s|%s|%s|%s|%s|%s|%s\n' "$__lv" "$__id" "$__nm" "$__cd" "$__ty" "$__en" "$__ro" \
        "$(lv_threshold "${__lv#lv}")" "$__m"
    done
    printf 'pool|-|%s/%s|-|-|-|-|%s|-\n' "$VG" "$POOL" "$(pool_threshold)"
  } >"$__t" 2>/dev/null
  __n=$(grep -c '^lv' "$__t" 2>/dev/null)
  if [ "${__n:-0}" -gt 0 ]; then
    say "Saved what QTS knows of this pool's volumes ($__n) for the check after the bring-up:"
    note "$__t"
  else
    warn "QTS's volume table $F_VOLCONF names no volume of $VG/$POOL."
    note "The check after the bring-up goes by what QTS writes there then: volume IDs and alert thresholds cannot be compared with the state before."
  fi
}

bringup_save() { # before every bring-up command: copies of what the scan reads and rewrites, one tag per bring-up
  local __f __n=0
  BRINGUP_TAG="bringup-$(date +%H%M%S)"
  for __f in "$CONFL/raid.conf" "$CONFL/qlvm.conf" "$CONFL/ssdcache.conf" "$CONFL/qdrbd.conf" \
    "$CONFL/tiering_schedule.conf" "$CONFL"/*.initlvm "$F_VOLCONF" "$F_LVMRT"; do
    if [ -f "$__f" ] && cp "$__f" "$LOGDIR/${__f##*/}.$BRINGUP_TAG" 2>/dev/null; then __n=$((__n + 1)); fi
  done
  if [ "$__n" -gt 0 ]; then
    say "Copied $__n files of QTS's storage configuration, as they are now, to:"
    note "$LOGDIR/<name>.$BRINGUP_TAG"
  else
    warn "No copy of QTS's storage configuration could be made in $LOGDIR."
  fi
  bringup_table
}

bringup_pre() { # what must hold before QTS scans the storage: 0 = go, 1 = stop, 2 = QTS's configuration is missing
  local __f
  if [ ! -e "$F_BOOTDONE" ]; then
    warn "QTS has not finished booting ($F_BOOTDONE is missing)."
    note "The volumes were not started and nothing was changed. Wait until the NAS has finished booting, or reboot it, then run step 5 again."
    return 1
  fi
  for __f in raid.conf qlvm.conf; do
    if [ ! -s "$CONFL/$__f" ]; then
      warn "QTS's storage configuration is missing: $CONFL/$__f is not there or empty."
      note "storage_util --sys_startup_p2 was not started and nothing was changed."
      return 2
    fi
  done
  return 0
}

bringup_p2() { # storage_util --sys_startup_p2 behind the checks and the copies; 1 = it did not run
  bringup_pre
  case $? in
    0) ;;
    2)
      # the way on is the rebuild, and only the operator takes it: the automatic run answers "no" here
      if ask_yn "Rebuild QTS's storage configuration from the disks (init_lvm.sh)?" n; then
        bringup_rebuild
        return $?
      fi
      note "Left as it is. Next: run step 5 again for the rebuild, or reboot the NAS."
      return 1
      ;;
    *) return 1 ;;
  esac
  bringup_save
  MOUNT_RAN=1
  run_daemon storage_util --sys_startup_p2
  say "(messages like 'Permission denied ... relocation_rate' and 'kill: you need to"
  say " specify whom to kill' are normal for this command)"
  return 0
}

cfg_diff() { # cfg_diff <before> <after>: QTS ini settings that differ, one "[section] key: old -> new" per line
  awk '
    FNR == 1 { f++; s = "" }
    /^[ \t]*\[/ { s = $0; gsub(/[][ \t\r]/, "", s); if (f == 1) S1[s] = 1; else S2[s] = 1; next }
    {
      p = index($0, "="); if (!p) next
      k = substr($0, 1, p - 1); gsub(/[ \t]/, "", k)
      v = substr($0, p + 1); gsub(/^[ \t]+|[ \t\r]+$/, "", v)
      if (k ~ /uuid/) next # QTS makes new ones at every scan
      if (f == 1) A[s "|" k] = v; else B[s "|" k] = v
    }
    END {
      for (x in A) {
        split(x, q, "|")
        if (!(x in B)) print "[" q[1] "] " q[2] ": " A[x] " -> (gone)"
        else if (A[x] != B[x]) print "[" q[1] "] " q[2] ": " A[x] " -> " B[x]
      }
      for (x in B) if (!(x in A)) { split(x, q, "|"); print "[" q[1] "] " q[2] ": (new) " B[x] }
      for (x in S1) if (!(x in S2)) print "[" x "] gone"
    }' "$1" "$2" 2>/dev/null | sort
}

bringup_rebuild() { # init_lvm.sh: the operator's decision only, behind a typed word; 1 = it did not run
  # never in the automatic run
  if [ -n "$AUTO" ]; then return 1; fi
  if [ ! -e "$F_BOOTDONE" ]; then
    warn "QTS has not finished booting ($F_BOOTDONE is missing): nothing was rebuilt."
    note "Wait until the NAS has finished booting, or reboot it, then run step 5 again."
    return 1
  fi
  if [ ! -x "$INITD/init_lvm.sh" ]; then
    warn "$INITD/init_lvm.sh is not on this NAS: nothing was rebuilt."
    return 1
  fi
  warn "The rebuild runs $INITD/init_lvm.sh. What it does:"
  note "It moves raid.conf, qlvm.conf, ssdcache.conf and qdrbd.conf in $CONFL aside as *.initlvm and builds them again from the disks. Volume IDs can change and alert thresholds can drop to 0 %. An earlier *.initlvm is overwritten. Copies of the files as they are now go to the log directory first:"
  note "$LOGDIR"
  if ! ask_word REBUILD; then
    say "Not rebuilt: QTS's storage configuration is unchanged."
    return 1
  fi
  bringup_save
  iscsi_conf_check save
  lvm_conf_check save
  # from here on bringup_check lists a difference from the saved table as the rebuild's doing, not as a fault
  date 2>/dev/null >"$LOGDIR/bringup.rebuilt"
  MOUNT_RAN=1
  run_daemon "$INITD/init_lvm.sh"
  iscsi_conf_check compare
  lvm_conf_check compare
  rebuild_diff
  return 0
}

rebuild_diff() { # every setting the rebuild changed in QTS's four storage files, against the copies made before it
  local __f __d="$LOGDIR/rebuild.diff" __n
  : 2>/dev/null >"$__d"
  for __f in raid.conf qlvm.conf ssdcache.conf qdrbd.conf; do
    if [ -f "$LOGDIR/$__f.$BRINGUP_TAG" ] && [ -f "$CONFL/$__f" ]; then
      cfg_diff "$LOGDIR/$__f.$BRINGUP_TAG" "$CONFL/$__f" | sed "s|^|$__f |" 2>/dev/null >>"$__d"
    fi
  done
  __n=$(grep -c . "$__d" 2>/dev/null)
  if [ "${__n:-0}" = 0 ]; then
    ok "The rebuild left every setting of raid.conf, qlvm.conf, ssdcache.conf and qdrbd.conf as it was."
    return 0
  fi
  warn "The rebuild changed $__n setting(s) in QTS's storage configuration (new IDs left out):"
  head -n 12 "$__d" | while IFS= read -r __f; do note "$__f"; done
  note "All of them: $__d. The files from before: $LOGDIR/<name>.$BRINGUP_TAG"
  note "Settings that matter (alert thresholds, RAID read-ahead) are set again in Storage & Snapshots."
}

# bringup_check: the state now against the saved table, one ok/warn line per volume. Checked: the thin pool and
# every LV of the table active, a cachedevN for each, every data volume (volType 1) mounted read-write, no new
# readOnly = yes, volume IDs, cachedevN numbers, mount points and alert thresholds as saved. An encrypted volume
# that is locked is no fault; a LUN needs its cachedevN and no mount; snapshots are not looked at.
# Sets BRINGUP_MISS and BRINGUP_CHG; 1 when something is missing or, without a rebuild, not as saved.
bringup_check() {
  local __t="$LOGDIR/bringup.expected" __rows __seen __now __cur __lv __id __nm __cd __ty __en __ro __th __mp0
  local __cid __ccd __m __mp __what __bad __x __rebuilt=""
  BRINGUP_MISS=""
  BRINGUP_CHG=""
  BRINGUP_IDS=""
  if [ -f "$LOGDIR/bringup.rebuilt" ]; then __rebuilt=1; fi
  lvtab
  __now=$(vol_rows "$F_VOLCONF")
  __rows=$(grep '^lv' "$__t" 2>/dev/null)
  __seen=" $(printf '%s\n' "$__rows" | awk -F'|' 'NF {printf "%s ", $1}')"
  # a data volume the saved table does not have is checked by what QTS says now
  for __lv in $(fs_volumes); do
    case "$__seen" in *" $__lv "*) continue ;; esac
    __cur=$(printf '%s\n' "$__now" | awk -F'|' -v l="$__lv" '$1 == l {printf "%s|?|%s|%s|%s|%s|%s|?|?\n", $1, $3, $4, $5, $6, $7; exit}')
    __rows="$__rows
${__cur:-$__lv|?|-|?|1|-|-|?|?}"
  done
  printf '%s\n' "$__rows" | grep . 2>/dev/null >"$LOGDIR/bringup.rows"
  say "Volumes of $VG/$POOL now, against the table saved before the bring-up:"
  case "$(lv_field "$POOL" 2)" in
    ????a*) ;;
    *)
      warn "Thin pool $VG/$POOL is not active."
      BRINGUP_MISS="$BRINGUP_MISS; thin pool $VG/$POOL is not active"
      ;;
  esac
  if [ ! -s "$LOGDIR/bringup.rows" ]; then
    warn "Neither QTS's volume table nor LVM names a volume of this pool: nothing could be checked."
    BRINGUP_MISS="$BRINGUP_MISS; no volume could be checked"
  fi
  while IFS='|' read -r __lv __id __nm __cd __ty __en __ro __th __mp0; do
    __x="$__nm ($__lv)"
    if [ "$__nm" = - ]; then __x=$__lv; fi
    __bad=""
    __what=""
    __ccd=$__cd
    __cur=$(printf '%s\n' "$__now" | awk -F'|' -v l="$__lv" '$1 == l {print; exit}')
    if [ "$__cd" = "?" ]; then
      __bad=", QTS's volume table does not name it, so it could not be checked"
    elif [ -z "$__cur" ]; then
      __bad=", QTS's volume table no longer names it"
    else
      __cid=$(printf '%s\n' "$__cur" | cut -d'|' -f2)
      __ccd=$(printf '%s\n' "$__cur" | cut -d'|' -f4)
      if [ "$__id" != "?" ] && [ "$__cid" != "$__id" ]; then # QTS numbers them anew at every scan: information only
        BRINGUP_IDS="$BRINGUP_IDS
$__x: volume ID $__id -> $__cid"
      fi
      if [ "$__ccd" != "$__cd" ]; then
        BRINGUP_CHG="$BRINGUP_CHG
$__x: $__cd -> $__ccd"
      fi
      if [ "$(printf '%s\n' "$__cur" | cut -d'|' -f7)" = yes ] && [ "$__ro" != yes ]; then
        __bad="$__bad, QTS set it read-only (readOnly = yes)"
      fi
    fi
    case "$(lv_field "$__lv" 2)" in
      ????a*) ;;
      '') __bad="$__bad, $__lv is gone from LVM" ;;
      *) __bad="$__bad, $__lv is not active" ;;
    esac
    if [ "$__ccd" != "?" ]; then
      if ! is_blk "$DEVMAP/$__ccd"; then __bad="$__bad, no device $__ccd"; fi
      if [ "$__ty" = 1 ]; then
        __m=$(vol_mount "$__ccd")
        __mp=${__m%%|*}
        if [ -z "$__m" ]; then
          if [ "$__en" = yes ] && ! is_blk "$DEVMAP/ce_$__ccd"; then
            __what="is encrypted and locked: unlock it in Storage & Snapshots"
          else
            __bad="$__bad, not mounted"
          fi
        else
          case ",${__m#*|}," in
            *,rw,*) __what="mounted at $__mp" ;;
            *) __bad="$__bad, mounted read-only at $__mp" ;;
          esac
          if [ "$__mp0" != "?" ] && [ "$__mp0" != - ] && [ "$__mp" != "$__mp0" ]; then
            BRINGUP_CHG="$BRINGUP_CHG
$__x: mount point $__mp0 -> $__mp"
          fi
        fi
      else
        __what="has its device $__ccd (an iSCSI LUN has no mount)"
      fi
    fi
    if [ "$__th" != "?" ]; then
      __m=$(lv_threshold "${__lv#lv}")
      if [ "$__m" != "$__th" ]; then
        BRINGUP_CHG="$BRINGUP_CHG
$__x: $(th_chg "$__th" "$__m")"
      fi
    fi
    if [ -n "$__bad" ]; then
      warn "$__x: ${__bad#, }"
      BRINGUP_MISS="$BRINGUP_MISS; $__x: ${__bad#, }"
    elif [ "$__id" = "?" ]; then
      ok "$__x $__what (not in the saved table)"
    else
      ok "$__x $__what"
    fi
  done <"$LOGDIR/bringup.rows"
  __m=$(awk -F'|' '$1 == "pool" {print $8; exit}' "$__t" 2>/dev/null)
  __x=$(pool_threshold)
  if [ -n "$__m" ] && [ "$__m" != "$__x" ]; then
    BRINGUP_CHG="$BRINGUP_CHG
pool $VG/$POOL: $(th_chg "$__m" "$__x")"
  fi
  if [ -n "$BRINGUP_IDS" ]; then
    say "QTS numbered the volumes anew (its scan does that every time; shares follow the mount point):"
    printf '%s\n' "$BRINGUP_IDS" | grep . | while IFS= read -r __x; do note "$__x"; done
  fi
  if [ -n "$BRINGUP_CHG" ]; then
    if [ -n "$__rebuilt" ]; then
      warn "The rebuild changed these settings (against the table saved before it):"
    else
      warn "Not as saved before the bring-up:"
      BRINGUP_MISS="$BRINGUP_MISS; QTS's settings of the volumes are not as saved"
    fi
    printf '%s\n' "$BRINGUP_CHG" | grep . | while IFS= read -r __x; do note "$__x"; done
    note "Alert thresholds are set in Storage & Snapshots: this script does not write QTS's configuration. The saved table: $__t"
  elif [ -n "$__rebuilt" ]; then
    ok "cachedevN numbers, mount points and alert thresholds are as saved."
  fi
  BRINGUP_MISS=${BRINGUP_MISS#; }
  [ -z "$BRINGUP_MISS" ]
}

bringup_fix() { # something is missing after the bring-up: the operator's three ways on; 0 = nothing is missing now
  while [ -n "$BRINGUP_MISS" ]; do
    if [ -n "$AUTO" ]; then return 1; fi # pick would take the first entry for the automatic run: it stops instead
    say "Not everything came back. What next?"
    PICK_LIST="run storage_util --sys_startup_p2 once more
rebuild QTS's storage configuration with init_lvm.sh (asks for a typed word)
leave it - I will do it by hand or reboot the NAS"
    pick "Choose" || return 1
    case "$PICK" in
      run*) bringup_p2 || continue ;;
      rebuild*) bringup_rebuild || continue ;;
      *) return 1 ;;
    esac
    run show_mounts
    bringup_check
  done
  return 0
}

startup_mount() { # QTS builds cachedevN and mounts the volumes: storage_util --sys_startup_p2, or the operator skips it
  say "Mounting the volumes through QTS:"
  PICK_LIST="storage_util --sys_startup_p2   (QTS builds cachedevN and mounts the volumes)
skip - I will do it by hand or reboot the NAS"
  MOUNT_RAN=""
  if pick "Choose"; then
    case "$PICK" in
      skip*) ;;
      *) bringup_p2 ;;
    esac
  fi
}

services_back() { # start what this script stopped: the QTS services, or the snapshot manager alone
  local __d=y
  if [ -n "$BRINGUP_MISS" ]; then __d=n; fi # apps started without their volume do not find their data
  if [ "$SERVICES_STOPPED" = 1 ]; then
    say "The QTS services were stopped by this script.${BRINGUP_MISS:+ A volume is still missing.}"
    if ask_yn "Start them again (lvmetad, then services.sh start)?" "$__d"; then
      if [ -x "$DAEMON_MGR" ]; then run_daemon "$DAEMON_MGR" lvmetad start "/sbin/lvmetad"; fi
      # after a boot with the pool down the apps on it have no /etc/rcS.d/QS* links and services.sh skips them;
      # qpkg --set-rc-seq makes the links (as init_qpkg.sh start does) and changes nothing when they exist
      if [ -x "$QPKG" ]; then run_daemon "$QPKG" --set-rc-seq; fi
      run_daemon "$INITD/services.sh" start
      SERVICES_STOPPED=""
      QSNAP_STOPPED=""
      save_state
    else
      note "The services stay stopped. Step 5 asks again; a NAS reboot starts them too."
    fi
    say "If the snapshot manager or the system log do not come back, reboot the NAS at a convenient time."
  elif [ "$QSNAP_STOPPED" = 1 ]; then
    if init_has "$INITD/qsnapman.sh" start; then
      if ask_yn "The snapshot manager was stopped. Start it (qsnapman.sh start)?" "$__d"; then
        run_daemon "$INITD/qsnapman.sh" start
        QSNAP_STOPPED=""
        save_state
      fi
    else
      say "The snapshot manager (qsnapman) was stopped and its init script takes no 'start':"
      say "it comes back after a NAS reboot."
    fi
  fi
}

mps_note() { # the mount points of the pool's volumes; mounts under them (apps, containers) only counted
  local __mp __n=0
  for __mp in $ST_MPS; do
    case "$__mp" in
      /share/CACHEDEV*_DATA | /share/CE_CACHEDEV*_DATA | /mnt/pool*) note "$__mp" ;;
      *) __n=$((__n + 1)) ;;
    esac
  done
  if [ "$__n" -gt 0 ]; then note "(and $__n mounts of apps and containers on these volumes)"; fi
}

trans_ids() { # after a failed activation: the pool's transaction_id as LVM holds it, next to the superblock's
  local __l
  __l=$(lvs --noheadings -o transaction_id "$VG/$POOL" 2>/dev/null | tr -cd '0-9')
  if [ -z "$__l" ] || [ -z "$SB_TRANS" ]; then return 0; fi
  if [ "$__l" = "$SB_TRANS" ]; then
    say "transaction_id of $VG/$POOL: LVM holds $__l, the metadata superblock $SB_TRANS (the same)."
  else
    say "transaction_id of $VG/$POOL: LVM holds $__l, the metadata superblock $SB_TRANS (they differ)."
  fi
}

_do_startup() {
  local __mp
  hdr "Bring the pool and the volumes up"
  if is_swapped; then
    if copy_live; then
      err "LVM is in the temporary state - finish step 4) Repair first."
      copy_live_note
    else
      err "LVM is in the temporary state - first 6) Tools -> c) undo the LVM swap."
    fi
    return 1
  fi
  if pool_is_online; then
    compute_stack
    if [ -n "$ST_MPS" ]; then
      # Already up, whatever the stage: a step 2 that stopped half way leaves services stopped and volumes
      # unmounted on an active pool. Check, offer the mount, start what was stopped; only "finish" needs final_ok.
      ok "The pool is active. Mounted now:"
      mps_note
      bringup_table
      if ! bringup_check; then
        if [ -n "$AUTO" ]; then # the automatic run does not start QTS commands on a pool that is already up
          warn "The automatic run stops here: mounting the missing volumes is your decision."
          note "Nothing was changed. Next: step 5 from the menu."
          return 1
        fi
        if ask_yn "Mount the missing volumes through QTS (storage_util --sys_startup_p2)?" y; then
          if bringup_p2; then
            run show_mounts
            bringup_check || bringup_fix
          fi
        fi
      fi
      services_back
      if [ -n "$BRINGUP_MISS" ]; then
        note "A volume with filesystem errors: 6) Tools -> o) checks it, or 'Check File System'"
        note "in Storage & Snapshots."
      fi
      if ! stage_ge final_ok; then
        if [ -z "$BRINGUP_MISS" ]; then ok "Every volume of the pool is back. The repair session stays open."; fi
        return 0
      fi
      if [ -n "$BRINGUP_MISS" ]; then
        if ask_yn "Something is still missing. Finish the repair session anyway?" n; then finish; fi
      else
        banner good
        if ask_yn "Mark the session as finished?" y; then finish; fi
      fi
      return 0
    fi
  fi
  if [ "$CLASS" = CLEAN ] && [ "$STAGE" = diagnosed ]; then
    say "The metadata was found clean - nothing was repaired, the pool is simply brought up."
  elif ! stage_ge final_ok; then
    warn "The repair has not been finished (stage: $(stage_desc "$STAGE"))."
    if [ "$COPY_LIVE" = 1 ]; then
      copy_live_note
      warn "Bringing the pool up now starts it on the out-of-date original and gives up those writes."
      ask_word START-ON-ORIGINAL || return 1
    else
      ask_yn "Bring the pool up anyway?" n || return 1
    fi
  fi
  clear_skip_flag
  dmesg 2>/dev/null >"$LOGDIR/dmesg.pre-start" # to tell new kernel messages from old ones afterwards
  run vgchange -an "$VG"
  runq lvchange -an -ff "$VG/$META"
  run vgchange -ay "$VG"
  cp "$LOGDIR/cmd.out" "$LOGDIR/activate.out" 2>/dev/null
  run lvs -a "$VG"
  if ! pool_is_online; then
    err "The pool did not activate."
    activation_hints "$LOGDIR/activate.out"
    trans_ids
    say "Kernel messages:"
    dmesg 2>/dev/null | tail -n 12
    return 1
  fi
  ok "Pool $VG/$POOL is active."
  fs_check || return 1
  startup_mount
  run lvs -a "$VG"
  run show_mounts
  # the success path below runs only when this check found nothing missing; the exit code of the command is not asked
  if ! bringup_check && [ -n "$MOUNT_RAN" ]; then
    if [ -n "$AUTO" ]; then # never a second scan or the rebuild without the operator
      compute_stack
      if [ -z "$ST_MPS" ]; then
        err "The mount command ran, but no volume of this pool is mounted - the session stays open."
      else
        warn "Not everything came back - the session stays open."
      fi
      note "The automatic run stops here: the next move is your decision. Step 5 from the menu offers storage_util once more, the rebuild of QTS's storage configuration, or leaving it."
      return 1
    fi
    bringup_fix
  fi
  lvtab
  if [ -x "$INITD/iscsitrgt.sh" ] && printf '%s\n' "$LVTAB" |
    awk -F'|' '$1 ~ /^lv[0-9]+$/ {n = substr($1, 3) + 0; if (n >= 288 && n <= 543) f = 1} END {exit !f}'; then
    if ask_yn "The pool holds iSCSI LUNs. Restart the iSCSI service (iscsitrgt.sh stop/start)?" n; then
      run_daemon "$INITD/iscsitrgt.sh" stop
      run_daemon "$INITD/iscsitrgt.sh" start
    fi
  fi
  services_back
  snapshot after-startup
  new_kernel_errors
  say "If QTS does not see the snapshots: 6) Tools -> f) rescan the snapshots."
  say "If a volume stays 'Read/Delete' although space is free: 6) Tools -> k) (reclaim tag)."
  say "If a volume stays 'Unmounted' or reports filesystem errors, run 'Check File System' in"
  say "Storage & Snapshots."
  if [ "$FSCK" = skip ]; then fs_pause_note; fi
  if stage_ge final_ok; then
    compute_stack
    if [ -z "$ST_MPS" ]; then
      if [ -n "$MOUNT_RAN" ]; then # a failure of this step, not the operator's "skip": fail_banner shows it
        err "The mount command ran, but no volume of this pool is mounted - the session stays open."
      else
        warn "No volume of this pool is mounted yet - the session stays open."
      fi
      note "Run this step again (or reboot the NAS) and finish the session once the volumes are up."
      return 1
    fi
    if [ -n "$BRINGUP_MISS" ]; then
      warn "Not everything came back (the lines marked [WARN] in the check above)."
      note "Run this step again, or use 'Check File System' in Storage & Snapshots."
      if ask_yn "Finish the repair session anyway?" n; then finish; fi
    else
      banner good
      say "Mounted:"
      mps_note
      if ask_yn "Data reachable - finish the repair session?" y; then finish; fi
    fi
  elif [ "$CLASS" = CLEAN ] && [ "$STAGE" = diagnosed ]; then # nothing was repaired: no session to finish, no question
    compute_stack
    if [ -n "$ST_MPS" ] && [ -z "$BRINGUP_MISS" ]; then
      banner good
      END_WAIT=1
    fi
  fi
  return 0
}

_finish() {
  set_stage "done"
  verify_mounts >/dev/null # the report lists the volumes as they are now, not as they were after the first start
  make_report
  pack_logs
  mv -f "$PERSIST/state" "$PERSIST/state.done-$(date +%Y%m%d-%H%M%S)" 2>/dev/null
  ok "Session finished."
  if [ -n "$BACKUP_FILE" ]; then note "Keep the copy of the original metadata: $BACKUP_FILE"; fi
  if [ -z "$VERIFY_MISS" ] && [ -z "$BRINGUP_MISS" ]; then # never after "Finish the repair session anyway?"
    printf '%s%s%s\n' "$C_G" "Pool $VG/$POOL is back online with all its volumes mounted. Let's rock." "$C_0"
    logf "Pool $VG/$POOL is back online with all its volumes mounted. Let's rock."
    END_WAIT=1
  fi
}

# ==================================================================================================
#  Tools
# ==================================================================================================
_tool_tpcollect() {
  local __src="" __c __id
  hdr "tp_collect.sh - log package for QNAP"
  require_offline || return 1
  need_workdir || return 1
  for __c in "$CWD/tp_collect.sh" "$WORKDIR/tp_collect.sh" /root/tp_collect.sh "$TMPD/tp_collect.sh"; do
    if [ -s "$__c" ]; then
      __src=$__c
      break
    fi
  done
  if [ -z "$__src" ]; then
    ask_yn "Download $URL_TPCOLLECT ?" y || return 1
    run wget "$URL_TPCOLLECT" -O "$WORKDIR/tp_collect.sh" || {
      rm -f "$WORKDIR/tp_collect.sh" # a partial file would be taken for a local copy at the next try
      err "Download failed."
      return 1
    }
    __src="$WORKDIR/tp_collect.sh"
    if ! trust_file "$__src" "$TPCOLLECT_SHA256" "Downloaded helper"; then
      mv -f "$__src" "$__src.not-run" 2>/dev/null
      say "Not run. The file is kept as $__src.not-run for inspection."
      return 1
    fi
  else
    say "Helper: $__src ($(file_digest "$__src"))"
  fi
  # with COLLECT= set, tp_collect writes to the work directory instead of
  # stopping md321/md322 and building the temporary md9000 array
  sed "s|^COLLECT=.*|COLLECT=$WORKDIR|" "$__src" >"$WORKDIR/tp_collect.run.sh"
  __id=${VG#vg}
  say "The result goes to $WORKDIR/collect (collect.tgz). When asked for the pool id, enter: $__id"
  (
    trap - INT QUIT
    umask "$UMASK0"
    cd "$WORKDIR" && sh ./tp_collect.run.sh 2>&1
  )
  logf "tp_collect finished rc=$?"
}

_tool_clear_flag() {
  hdr "Clearing the needs_check flag on $META"
  cache_gate || return 1
  require_offline || return 1
  meta_up || return 1
  pick_pdata || return 1
  clear_flag_if_set "$METADEV"
}

_tool_restore_backup() {
  local __want __got
  hdr "EMERGENCY: restore the original metadata from the backup"
  require_offline || return 1
  meta_up || return 1
  pick_pdata || return 1
  if [ -z "$BACKUP_FILE" ] || [ ! -s "$BACKUP_FILE" ]; then
    err "No backup file ($BACKUP_FILE)."
    return 1
  fi
  # before the write: the image has to be intact and exactly as large as the device
  __want=$(blockdev --getsize64 "$METADEV" 2>/dev/null)
  if [ "$BACKUP_KIND" = gz ]; then
    run_long gzip -t "$BACKUP_FILE" || {
      err "The archive failed its test - not restoring from it."
      return 1
    }
    run_long gz_size "$BACKUP_FILE"
    __got=$(tail -n 1 "$LOGDIR/cmd.out" | tr -d ' ')
  else
    __got=$(fsize "$BACKUP_FILE")
  fi
  if [ -n "$__want" ] && [ "$__got" != "$__want" ]; then
    err "The image holds $__got B, the metadata device $__want B - not restoring from it."
    return 1
  fi
  warn "The contents of $VG/$META will be replaced with the image: $BACKUP_FILE"
  note "This brings back the state from BEFORE the repair (including the original errors)."
  ask_word RESTORE || return 1
  RL_CRIT=1
  if [ "$BACKUP_KIND" = gz ]; then
    run_long gz_restore "$BACKUP_FILE" "$METADEV"
  else
    run_long dd "if=$BACKUP_FILE" "of=$METADEV" bs=4194304
  fi
  RL_CRIT=""
  if [ "$RC" != 0 ]; then
    err "The restore ended with an error (rc=$RC)."
    return 1
  fi
  run sync
  # after the write: read the device back and compare it with the image
  say "Reading the device back and comparing it with the image..."
  run_long same_data "$BACKUP_FILE" "$METADEV" "$BACKUP_KIND"
  case "$RC" in
    0) ok "The device is identical to the image." ;;
    2) warn "No cmp or md5sum on this NAS - the read-back comparison was skipped." ;;
    *)
      err "The device differs from the image after the restore. Stop and investigate before anything else."
      return 1
      ;;
  esac
  # a separate diagnostic: the image carries the original errors, so "not clean" is expected here
  thin_check_run "$METADEV" restored
  say "State after the restore: $TC_CLASS ($TC_INFO)"
  CLASS=$TC_CLASS
  RPATH=""
  FSCK=""
  ORIG_TC=$TC_FILE
  DIAG_TC=${TC_FILE##*/}
  set_stage backed_up
}

_tool_snapscan() {
  hdr "Rescan the snapshots"
  say "Use only when QTS does not see the snapshots after the repair (the snapshot config is set aside)."
  ask_yn "Run it?" n || return 1
  run mv /etc/config/qsnapshot/snapshot.conf /etc/config/qsnapshot/snapshot.conf-
  run mv /etc/config/qsnapshot/snapshotStatus.conf /etc/config/qsnapshot/snapshotStatus.conf-
  run_long storage_util --snapshot_scan
}

_tool_restoremissing() { # per the case study "LVM PV became in missing mode"
  local __pv
  hdr "PV in missing mode: vgextend --restoremissing"
  lvm_check
  run pvs
  if [ -z "$PV_MISSING" ]; then
    ok "No PV of $VG is in missing mode."
    return 0
  fi
  raid_check
  say "RAID under $VG: $RAID_SUM"
  for __pv in $PV_MISSING; do
    if [ "$__pv" = unknown ]; then
      err "A PV shows as 'unknown device' - that device does not exist on this system."
      note "Go back to the RAID/DRBD layer: md_checker, mdadm -AfR, drbdadm up rN, drbdadm primary rN."
      continue
    fi
    say "Device $__pv is present, but LVM has flagged it as missing."
    if ask_yn "Run: vgextend $VG --restoremissing $__pv ?" n; then
      run vgextend "$VG" --restoremissing "$__pv"
    fi
  done
  lvm_check
  if [ -z "$PV_MISSING" ]; then
    ok "All PVs of $VG are available."
    note "Next: step 5) Bring the pool and the volumes up."
  fi
}

_tool_fullrescan() { # Recover NAS SOP, method 3: re-create the storage configuration with a volume scan
  local __f
  hdr "LAST RESORT: full storage configuration rescan"
  say "For the case where the volumes mount by hand but do not come back after a reboot."
  say "The QTS storage configuration is set aside and rebuilt by a scan (Recover NAS SOP, method 3):"
  note "vgchange -an $VG"
  note "$CONFD/qdrbd.conf qlvm.conf ssdcache.conf raid.conf  ->  <name>-"
  note "storage_util --volume_scan do_scan_raid=0,force=1"
  warn "Do not use it before everything else has been done."
  ask_word RESCAN || return 1
  run vgchange -an "$VG"
  for __f in qdrbd.conf qlvm.conf ssdcache.conf raid.conf; do
    if [ -e "$CONFD/$__f" ]; then run mv "$CONFD/$__f" "$CONFD/$__f-"; fi
  done
  run_daemon storage_util --volume_scan do_scan_raid=0,force=1
  if [ "$RC" != 0 ]; then
    note "If DRBD blocks the scan (same SOP), per RAID group N: drbdadm down rN ; yes yes | drbdadm create-md rN ; drbdadm up rN ; drbdadm down rN ; then the volume_scan again."
  fi
  note "If storage_util hangs: cat /proc/locks ; cat /proc/<pid>/stack ; kill -9 <pid>"
}

_tool_orphans() { # "pdata_tools usage": missing mappings may still sit in orphan nodes of the metadata
  local __ll __starts __s __hits
  hdr "thin_ll_dump: look for orphan nodes that cover the missing mappings"
  require_offline || return 1
  need_workdir || return 1
  meta_up || return 1
  pick_pdata || return 1
  if [ -z "$ORIG_TC" ] || [ ! -s "$ORIG_TC" ]; then
    thin_check_run "$METADEV" original
    ORIG_TC=$TC_FILE
  fi
  __starts=$(sed -n 's/.*is missing mappings \[\([0-9][0-9]*\),.*/\1/p' "$ORIG_TC" | sort -un)
  if [ -z "$__starts" ]; then
    ok "thin_check reports no missing mappings."
    return 0
  fi
  __ll="$WORKDIR/thin_ll_dump.log"
  run_long "$PDATA" thin_ll_dump "$METADEV" -o "$__ll"
  if [ "$RC" != 0 ] || [ ! -s "$__ll" ]; then
    err "thin_ll_dump failed (rc=$RC)."
    return 1
  fi
  for __s in $__starts; do
    __hits=$(grep "key_begin=\"$__s\"" "$__ll")
    if [ -n "$__hits" ]; then
      ok "Missing range starting at $__s - nodes with that key_begin:"
      printf '%s\n' "$__hits" | head -n 10
      logf "orphan candidates for $__s: $__hits"
    else
      say "Missing range starting at $__s: no node starts there."
    fi
  done
  say "Dump: $__ll"
  note "Per the SOP: copy the device list of that dump into a restore.xml, add the matching orphan"
  note "<node .../> line (the leaf, flags=\"2\", whose key range fits) under its <device>, then build the working copy with it: step 4, 'another method', 'll restore' (thin_ll_restore -E)."
}

_tool_sbrestore() { # "Thin debug usage" 5-6: corrupt superblock, restored from one of its backup copies
  local __blk
  hdr "Restore the metadata superblock from a backup (thin_patch --restore-superblock)"
  cache_gate || return 1
  require_offline || return 1
  meta_up || return 1
  pick_pdata || return 1
  thin_check_run "$METADEV" original
  if [ "$TC_CLASS" != SUPERBLOCK ]; then
    ok "thin_check reads the superblock (result: $TC_CLASS) - nothing to restore."
    if [ "$RPATH" != superblock ]; then return 0; fi
    say "The diagnosis is out of date - running it again."
    RPATH=""
    do_diag
    return 1
  fi
  __blk=$(sed -n 's/.*valid superblock backups, last backup_id=[0-9]* blocknr=\([0-9][0-9]*\).*/\1/p' "$TC_FILE" | head -n 1)
  if [ -z "$__blk" ]; then
    say "thin_check names no valid backup. Take the block number of a backup superblock from an earlier thin_check log: '... valid superblock backups, last backup_id=N blocknr=B'."
    rd "Block number of the backup superblock (empty = cancel): "
    case "$ANS" in '' | *[!0-9]*) return 1 ;; esac
    __blk=$ANS
  fi
  say "Checking the metadata through the backup superblock at block $__blk (read-only):"
  thin_check_run "$METADEV" sb-backup "-m$__blk"
  say "Through the backup superblock: $TC_CLASS ($TC_INFO)"
  if [ "$TC_CLASS" = SUPERBLOCK ] || [ "$TC_CLASS" = UNKNOWN ]; then
    err "That backup superblock is not usable either - escalate with the tp_collect package (6a)."
    return 1
  fi
  backup_gate || return 1
  warn "thin_patch writes the superblock of the original metadata ($VG/$META)."
  ask_word YES || return 1
  snapshot before-thin_patch
  RL_CRIT=1
  run_long "$PDATA" thin_patch --restore-superblock "$METADEV"
  RL_CRIT=""
  if [ "$RC" != 0 ]; then
    err "thin_patch ended with an error (rc=$RC)."
    return 1
  fi
  run sync
  ORIG_TC=""
  do_diag || return 1
  if [ "$CLASS" != CLEAN ] || [ "$TC_CLASS" != CLEAN ]; then
    if [ "$TC_CLASS" != CLEAN ]; then
      warn "The superblock is back, the metadata still has errors ($TC_CLASS) - go on with step 4) Repair."
    fi
    return 1
  fi
  if flag_odd "$SB_FLAGS"; then clear_flag_if_set "$METADEV" || return 1; fi
  ok "Superblock restored: thin_check found no errors."
  RPATH=superblock
  set_stage final_ok
  return 0
}

tool_reference() { # what the related SOPs do for the cases this script does not automate
  hdr "Reference: neighbouring problems and what their SOPs do"
  cat <<EOF
 RAID      array inactive, members missing       md_checker ; mdadm -E /dev/sdX3 ; mdadm -AfR /dev/mdN <members>
 DRBD      PV on /dev/drbdN is gone              ls /etc/config/ha/r*.res ; drbdadm up rN ; drbdadm disconnect rN ;
                                                 drbdadm primary rN --force
 LVM       header lost, PV 'unknown device'      copy in /etc/config/lvm/backup/vgN (or .../archive), PV id inside:
                                                 pvcreate /dev/mdN --uuid <PV id> --restorefile <copy> ;
                                                 vgcfgrestore vgN -f <copy> --force ; pvscan --cache
 LVM       Refusing activation of partial LV     Tools -> i  (vgextend --restoremissing)
 LVM       transaction_id=X, while expected Y    correct transaction_id of the pool in a vgcfgbackup file, then
                                                 vgcfgrestore --force (KB 'transaction id mismatch')
 LVM       reload ioctl: Invalid argument        dmesg 'too small for target': RAID/DRBD smaller than its LVs
 SSD cache pool will not activate on QTS 5.0.0   'fcorig' SOP; lvs -a -o+cachemode,cacheiomode first:
                                                 read-only cache = LVM header edit, read-write cache = escalate
 SSD cache cache metadata errors                 pdata_tools cache_check / cache_dump --repair / cache_restore
 Thin pool superblock corrupt, backups valid     Tools -> m  (thin_patch --restore-superblock)
 Thin pool keys are out of order                 step 4, 'another method': the 'skip out of order' pdata_tools build
 Thin pool missing mappings + orphan nodes       Tools -> l, then 'll restore' with a restore.xml
 Thin pool reference counts (ghost snapshots)    quick path, or 'rebuild' with QNAP's thin_rebuild build
 Thin pool volumes cannot be unmounted at all    lvchange -ky vgN ; reboot ; repair ; lvchange -kn vgN  (offered at step 2)
 QTS       volume stays Read/Delete afterwards   copy /etc/.sm_v2_storage_runtime_info, remove [Pool_N] need_reclaim /
                                                 snapshot_reserve_low, unmount the volume, storage_util --sys_startup_p2
 QTS       LUNSectorSize 0 after init_lvm.sh     setcfg LUN<n>Info LUNSectorSize <512|4096> -f /etc/config/iscsi_trgt.conf
 QTS       storage_util hangs                    cat /proc/locks ; cat /proc/<pid>/stack ; kill -9 <pid>
EOF
}

_tool_settings() {
  hdr "Session settings"
  say "Scratch LV: ${TMPLV:-none}   tool: ${PDATA:-auto}   directory: ${WORKDIR:-none}"
  if stage_ge tmp_ok && ! stage_ge final_ok; then
    err "A repair is in progress - the settings are locked."
    return 1
  fi
  PICK_LIST="change the scratch LV
re-detect pdata_tools
change the work directory"
  pick "What to change" || return 0
  case "$PICK" in
    *scratch*)
      TMPLV=""
      detect_tmplv ask
      ;;
    *pdata*)
      PDATA=""
      if meta_up; then pick_pdata; fi
      ;;
    *directory*) choose_workdir ;;
  esac
  save_state
}

_tools_menu() {
  while :; do
    hdr "Tools"
    cat <<EOF
  a) tp_collect.sh - log package for QNAP (written to the work directory)
  b) clear the needs_check flag on the original $META
  c) undo the temporary LVM swap (restore the original configuration)
  d) EMERGENCY: restore the original metadata from the backup
  e) stop the QTS services (services, qsnapman, lvmetad, qulog)
  f) rescan the snapshots (when QTS does not see them)
  g) shell (sh) - come back with: exit
  h) session settings (scratch LV, pdata_tools, directory)
  i) restore a PV in missing mode (vgextend --restoremissing)
  j) LAST RESORT: full storage configuration rescan (volume_scan)
  k) reference: neighbouring problems and what their SOPs do
  l) thin_ll_dump: look for orphan nodes that cover the missing mappings
  m) restore the metadata superblock from a backup (thin_patch)
  n) hardware check: kernel log, RAID members, memory
  o) filesystem check of the data volumes (read-only first; volumes not mounted)
  p) self-test of the commands this script uses (read-only)
  0) back
EOF
    rd "Choice: "
    case "$ANS" in
      a | A) tool_tpcollect ;;
      b | B) tool_clear_flag ;;
      c | C)
        hdr "Undo the LVM swap"
        if copy_live; then
          copy_live_note
          warn "Undoing the swap gives up every write the pool took on the working copy."
          note "Only for a pool that was never written to on the copy (an interrupted test on an LVM without the flag)."
          ask_word UNDO-SWAP || continue
        fi
        if unswap; then
          COPY_LIVE=""
          if [ "$STAGE" = swapped ]; then set_stage tmp_ok; else save_state; fi
        fi
        ;;
      d | D) tool_restore_backup ;;
      e | E) if ask_yn "Stop the QTS services?" n; then stop_services; fi ;;
      f | F) tool_snapscan ;;
      g | G) (
        trap - INT QUIT TSTP
        umask "$UMASK0"
        sh -i 2>&1
      ) ;;
      h | H) tool_settings ;;
      i | I) tool_restoremissing ;;
      j | J) tool_fullrescan ;;
      k | K) tool_reference ;;
      l | L) tool_orphans ;;
      m | M) tool_sbrestore ;;
      n | N)
        hdr "Hardware check"
        health_check
        ;;
      o | O) fs_check force ;;
      p | P) selftest ;;
      0 | '') return 0 ;;
    esac
  done
}

# ==================================================================================================
#  Hardware under the pool: kernel log, RAID members, DRBD role, memory
#    Pool metadata does not get damaged by itself: the cause is usually below it (RAM, disks, power).
#    thin_repair and e2fsck keep their working data in memory, so faulty or short memory matters.
# ==================================================================================================
mem_avail_mb() { # free memory plus free swap, MiB
  awk '/^MemAvailable:/ {a = $2} /^MemFree:/ {f = $2} /^Cached:/ {c = $2} /^SwapFree:/ {s = $2}
    END {if (a == "") a = f + c; printf "%d", (a + s) / 1024}' "$F_MEMINFO" 2>/dev/null
}

mem_note() { # warn when little memory is left for thin_repair / e2fsck
  local __m
  __m=$(mem_avail_mb)
  case "$__m" in '' | *[!0-9]*) return 0 ;; esac
  if [ "$__m" -lt 1024 ]; then
    warn "Only $__m MiB of memory and swap are free."
    note "thin_repair and e2fsck keep their working data in memory; when it runs out the kernel kills them (the original metadata stays untouched in that case). Free memory first or add swap on another volume: dd a file there, mkswap, swapon."
  else
    dbg "memory + swap free: $__m MiB"
  fi
}

health_check() { # sets HEALTH_MEM, HEALTH_IO, HEALTH_OOM (kernel log line counts), HEALTH_BB, HEALTH_DRBD
  local __f __p __m __dev __mds="" __bb __role __examined="" __own="" __members="" __io __oth __det="" __mce
  __f="$LOGDIR/health-$(date +%H%M%S).txt"
  HEALTH_DONE=1
  HEALTH_BB=""
  HEALTH_DRBD=""
  dmesg 2>/dev/null >"$LOGDIR/dmesg.now"
  # Reports of an error only: "[Hardware Error]: ...", "Machine check events logged", "Machine Check Exception",
  # "mce: ... Bank 4: ...", "EDAC MC0: 1 CE ..." / "... UE ...". Not the lines every boot prints:
  # "mce: Machine check injector initialized", "mce: CPU supports 7 MCE banks", "EDAC MC: Ver: 3.0.0".
  __mce='\[Hardware Error\]|machine check (events logged|exception)|mce: .*bank [0-9]|EDAC MC[0-9]+: [0-9]+ (CE|UE)'
  HEALTH_MEM=$(grep -ciE "$__mce" "$LOGDIR/dmesg.now" 2>/dev/null)
  HEALTH_OOM=$(grep -ciE 'out of memory|oom-killer' "$LOGDIR/dmesg.now" 2>/dev/null)
  HEALTH_MEM=${HEALTH_MEM:-0}
  HEALTH_OOM=${HEALTH_OOM:-0}
  for __p in $(pvs --noheadings -o pv_name,vg_name 2>/dev/null | awk -v v="$VG" '$2==v {print $1}'); do
    case "$__p" in
      /dev/md[0-9]*) __mds="$__mds ${__p#/dev/}" ;;
      /dev/drbd[0-9]*)
        __mds="$__mds md${__p#/dev/drbd}"
        __own="$__own ${__p#/dev/}"
        if [ -r "$F_DRBD" ]; then
          __role=$(awk -v n="${__p#/dev/drbd}:" '$1 == n { for (i = 2; i <= NF; i++) if ($i ~ /^ro:/) print $i }' "$F_DRBD")
          case "$__role" in '' | ro:Primary/*) ;; *) HEALTH_DRBD="$__p $__role" ;; esac
        fi
        ;;
    esac
  done
  for __m in $__mds; do
    __own="$__own $__m"
    for __dev in $(awk -v m="$__m" '$1 == m && $2 == ":" { for (i = 3; i <= NF; i++) if ($i ~ /^[a-z0-9]+\[[0-9]+\]/) { d = $i; sub(/\[.*/, "", d); print d } }' "$F_MDSTAT" 2>/dev/null); do
      __members=1
      __own="$__own $__dev" # the member (sda3, nvme0n1p3) and the disk it is a partition of (sda, nvme0n1)
      case "$__dev" in
        nvme* | mmcblk*) __own="$__own ${__dev%p[0-9]*}" ;;
        *) __own="$__own $(printf '%s' "$__dev" | sed 's/[0-9]*$//')" ;;
      esac
      if have mdadm; then
        __examined=1
        __bb=$(mdadm --examine-badblocks "/dev/$__dev" 2>/dev/null | grep -c ' for [0-9][0-9]* sectors')
        if [ "${__bb:-0}" -gt 0 ]; then HEALTH_BB="$HEALTH_BB $__dev($__bb)"; fi
      fi
    done
  done
  # Disk I/O error lines, sorted by the device name each one carries (any word of the line that is a block
  # device name: "dev sda,", "on device dm-3", "(device md1)", "[sdb]"):
  #   - a device under this pool: the md arrays above, their members and disks, drbdN, and the dm-N of this
  #     VG (they exist only while the pool is active) - counted
  #   - only other devices (a work disk on nbd0, a USB disk, another pool) - shown, not counted
  #   - no device name (ataN lines: a port is not tied to a member here) - counted
  # With no RAID member found under the VG every line is counted, as before.
  if [ -z "$__members" ]; then __own=""; fi
  if [ -n "$__own" ]; then
    __own="$__own $(dm_list | awk -F: -v pfx="$VGDM-" 'index($1, pfx) == 1 { printf "dm-%s ", $3 }')"
  fi
  __io=$(awk -v own=" $__own " '
    /I\/O error|[Mm]edium [Ee]rror|failed command: (READ|WRITE)|exception Emask/ {
      n = split($0, t, /[^A-Za-z0-9_-]+/); mine = 0; other = ""
      for (i = 1; i <= n; i++) {
        if (t[i] == "") continue
        if (index(own, " " t[i] " ")) mine = 1
        else if (t[i] ~ /^(sd[a-z][a-z]?[0-9]*|hd[a-z][0-9]*|nvme[0-9]+n[0-9]+(p[0-9]+)?|mmcblk[0-9]+(p[0-9]+)?|md[0-9]+|drbd[0-9]+|dm-[0-9]+|nbd[0-9]+(p[0-9]+)?|loop[0-9]+|sr[0-9]+)$/) other = other " " t[i]
      }
      if (mine || other == "" || own ~ /^ *$/) { io++; next }
      oth++
      m = split(other, o, " ")
      for (i = 1; i <= m; i++) if (!(o[i] in seen)) { seen[o[i]] = 1; names = names " " o[i] }
    }
    END { printf "%d %d%s\n", io, oth, names }' "$LOGDIR/dmesg.now" 2>/dev/null)
  HEALTH_IO=${__io%% *}
  HEALTH_IO=${HEALTH_IO:-0}
  __oth=${__io#* }
  case "$__oth" in '' | 0 | 0\ *) __oth="" ;; esac # else "<lines> <device> <device>..."
  {
    printf 'memory error lines: %s\ndisk I/O error lines: %s\nout-of-memory lines: %s\n' "$HEALTH_MEM" "$HEALTH_IO" "$HEALTH_OOM"
    printf 'devices under the pool:%s\n' "${__own:- none recognised (every I/O error line is counted)}"
    printf 'I/O error lines about other devices (not counted): %s\n' "${__oth:-0}"
    printf 'RAID members with bad blocks:%s\nDRBD: %s\n' "${HEALTH_BB:- none}" "${HEALTH_DRBD:-ok / not used}"
    printf '\n--- matching kernel lines (latest 40)\n'
    grep -iE "$__mce"'|I/O error|medium error|failed command: (READ|WRITE)|exception Emask|out of memory|oom-killer' "$LOGDIR/dmesg.now" | tail -n 40
  } >"$__f" 2>/dev/null
  if [ "$HEALTH_MEM" = 0 ] && [ "$HEALTH_IO" = 0 ] && [ "$HEALTH_OOM" = 0 ] && [ -z "$HEALTH_BB" ] && [ -z "$HEALTH_DRBD" ]; then
    ok "Hardware: nothing alarming in the kernel log${__examined:+, no bad blocks recorded on the RAID members}."
  else
    if [ "$HEALTH_MEM" != 0 ]; then warn "Hardware: $HEALTH_MEM memory error line(s) in the kernel log (machine check / EDAC)."; fi
    if [ "$HEALTH_IO" != 0 ]; then warn "Hardware: $HEALTH_IO disk I/O error line(s) in the kernel log."; fi
    if [ "$HEALTH_OOM" != 0 ]; then warn "Kernel: $HEALTH_OOM out-of-memory line(s) - a tool may have been killed."; fi
    if [ -n "$HEALTH_BB" ]; then warn "RAID: members with recorded bad blocks:$HEALTH_BB"; fi
    if [ -n "$HEALTH_DRBD" ]; then
      warn "DRBD: $HEALTH_DRBD - LVM can write only while the device is Primary (drbdadm primary rN)."
    fi
    sed -n '/^--- matching/,$p' "$__f" | tail -n 6
    note "Details: $__f"
    __det=1
  fi
  if [ -n "$__oth" ]; then
    say "${__oth%% *} I/O error line(s) in the kernel log are about other devices (${__oth#* }): not under this pool, not counted."
    if [ -z "$__det" ]; then note "Details: $__f"; fi
  fi
  logf "health: mem=$HEALTH_MEM io=$HEALTH_IO oom=$HEALTH_OOM bb=[$HEALTH_BB] drbd=[$HEALTH_DRBD] io-other=[$__oth]"
  mem_note
}

hw_gate() { # before every writing step: do not build new metadata on hardware that reports errors
  if [ -z "$HEALTH_DONE" ]; then health_check; fi
  if [ "${HEALTH_MEM:-0}" != 0 ] && [ -z "$HW_ACK" ]; then
    warn "The kernel log reports hardware memory errors ($HEALTH_MEM line(s))."
    note "thin_repair builds the new metadata in memory: on faulty RAM the result can be wrong in ways thin_check does not see. Test the RAM first (MemHound) and replace what fails."
    ask_yn "Continue on this hardware anyway?" n || return 1
    HW_ACK=1
  fi
  if { [ "${HEALTH_IO:-0}" != 0 ] || [ -n "$HEALTH_BB" ]; } && [ -z "$IO_ACK" ]; then
    warn "Disk errors under the pool (I/O error lines: ${HEALTH_IO:-0}; bad blocks:${HEALTH_BB:- none})."
    note "Check the disks (SMART) and the RAID before metadata is written through them."
    ask_yn "Continue anyway?" n || return 1
    IO_ACK=1
  fi
  return 0
}

tiers_used() { # how many tiers hold data, from the superblock line of thin_dump -b (0 without those fields)
  printf '%s\n' "$SB_LINE" | awk '{ n = 0; for (i = 1; i <= NF; i++) if ($i ~ /^tier[0-9]+_data_blocks="[1-9]/) n++; print n + 0 }'
}

# ==================================================================================================
#  Filesystem check before the first read-write mount
#    A repair that drops mappings leaves holes under the filesystem. The check runs on the thin LV
#    itself, before QTS builds cachedevN and mounts it: read-only first, a repair only on request.
#    Once cachedevN exists (the check was started after the bring-up) the repair runs on cachedevN.
# ==================================================================================================
fs_volumes() { # the thin data volumes of the pool (lv1-lv255), one per line; uses the current LVTAB
  printf '%s\n' "$LVTAB" | awk -F'|' -v p="$POOL" '$4 == p && $2 ~ /^V/ && $1 ~ /^lv[0-9]+$/ {
    n = substr($1, 3) + 0; if (n >= 1 && n <= 255) print $1 }'
}

fs_pause_note() {
  say "Until the filesystem on these volumes has been checked, keep off whatever writes or discards:"
  note "snapshot schedules, space reclamation, Qtier relocation, backup and sync jobs to these volumes."
}

# e2fsck_one <n|p|y> <volume> [backup superblock] [device]: e2fsck -f<mode> on the thin LV, or on the device
# given; the exit code is left in RC.
# The code is a set of flags: 1 corrected, 2 reboot, 4 errors left, 8 operational error, 16 usage, 32 cancelled.
e2fsck_one() {
  RL_SAVE="$LOGDIR/e2fsck-$2-$1${3:+-b$3}-$(date +%H%M%S).log"
  if [ "$1" != n ]; then RL_CRIT=1; fi
  if [ -n "$3" ]; then
    run_long "$E2FSCK" "-f$1" -b "$3" "${4:-$(dev_of "$2")}"
  else
    run_long "$E2FSCK" "-f$1" "${4:-$(dev_of "$2")}"
  fi
  RL_CRIT=""
  RL_SAVE=""
  case "$RC" in '' | *[!0-9]*) RC=255 ;; esac
  return 0
}

# sb_find <device>: which superblock opens, read-only (dumpe2fs -h lists it). SB_BLOCK = "" for the primary, or
# the first backup that opens, at the standard places of a filesystem with 4 KiB blocks; 1 = none opens.
sb_find() {
  local __d="" __b
  SB_BLOCK=""
  if have dumpe2fs_64; then __d=dumpe2fs_64; elif have dumpe2fs; then __d=dumpe2fs; fi
  if [ -z "$__d" ]; then # no tool to look with: e2fsck gets the primary
    note "dumpe2fs is not on this system: a backup superblock cannot be looked up, e2fsck starts from the primary."
    return 0
  fi
  if runq "$__d" -h "$1" || grep -q '^Block count:' "$LOGDIR/cmd.out"; then return 0; fi
  for __b in 32768 98304 163840 229376 294912 819200 884736 1605632 2654208 4096000 7962624 11239424 20480000 23887872; do
    if runq "$__d" -h -o "superblock=$__b" -o blocksize=4096 "$1" || grep -q '^Block count:' "$LOGDIR/cmd.out"; then
      SB_BLOCK=$__b
      return 0
    fi
  done
  return 1
}

_fs_check() { # fs_check [force]
  local __vols="" __v __n __bad="" __unk="" __mode __left __sb __b __dev
  if [ "$1" != force ]; then
    if [ -n "$FSCK" ]; then return 0; fi
    case "$CLASS" in MAPPING | SUPERBLOCK | UNKNOWN) ;; *) return 0 ;; esac
    if ! stage_ge final_ok; then return 0; fi
  fi
  hdr "Filesystem check before the volumes are mounted for writing"
  if [ "$1" != force ]; then
    say "The repair dropped the damaged mappings: blocks in those ranges now read as empty, so the filesystem on the affected volumes can be inconsistent. A read-only check (e2fsck -fn) shows the scale before QTS mounts the volume read-write and replays the journal on top of it."
  fi
  E2FSCK=""
  if have e2fsck_64; then E2FSCK=e2fsck_64; elif have e2fsck; then E2FSCK=e2fsck; fi
  if [ -z "$E2FSCK" ]; then
    warn "e2fsck_64 is not on this system: run 'Check File System' in Storage & Snapshots after the start."
    return 0
  fi
  if lvs --noheadings -o lv_name 2>/dev/null | grep -q '^ *lv256 *$'; then
    warn "An SSD cache volume (lv256) exists: the thin LV alone may not hold the latest data."
    note "Not checking below the cache - use 'Check File System' in Storage & Snapshots after the start."
    FSCK=skip
    save_state
    return 0
  fi
  lvtab
  for __v in $(fs_volumes); do
    case " $AFFECTED " in *" $__v "*) __vols="$__vols $__v" ;; esac
  done
  if [ -z "$__vols" ]; then __vols=$(fs_volumes); fi # thin_check named none of them: all data volumes
  __vols=$(echo $__vols)
  if [ -z "$__vols" ]; then
    say "The pool has no data volumes (lv1-lv255) to check."
    return 0
  fi
  say "Volumes to check: $__vols"
  mem_note
  note "On a large volume this runs for hours. The first pass only reads; to stop it, run 'killall $E2FSCK' in a second SSH session."
  if ! ask_yn "Run the read-only check now?" y; then
    FSCK=skip
    save_state
    fs_pause_note
    return 0
  fi
  for __v in $__vols; do
    __n=${__v#lv}
    if ! is_blk "$(dev_of "$__v")"; then
      warn "$__v is not active - skipped."
      __unk="$__unk $__v"
      continue
    fi
    if awk -v a="cachedev$__n" '{ d = $1; sub(/.*\//, "", d); if (d == a || d == "ce_" a) f = 1 } END { exit !f }' "$F_MOUNTS"; then
      warn "$__v is mounted (cachedev$__n): the check needs it unmounted - skipped."
      __unk="$__unk $__v"
      continue
    fi
    # e2fsck prints "Bad magic number in super-block" on an encrypted volume too: ask cryptsetup first
    if have cryptsetup && runq cryptsetup isLuks "$(dev_of "$__v")"; then
      warn "$__v: encrypted volume (LUKS), no ext4 filesystem directly on the LV - not checked."
      note "Check it from QTS after unlocking it."
      __unk="$__unk $__v"
      continue
    fi
    e2fsck_one n "$__v"
    __sb="" # the primary superblock is damaged: e2fsck went on with a backup copy (backup) or found none (none)
    if grep -qiE 'bad magic|trying backup blocks' "$LOGDIR/cmd.out"; then
      __sb=backup
      if grep -qiE 'valid ext[234]' "$LOGDIR/cmd.out"; then __sb=none; fi
    fi
    if [ "$RC" -ge 16 ]; then # usage, cancelled (killall), killed, did not start: whatever else is set says nothing
      warn "$__v: e2fsck could not finish (rc=$RC)."
      __unk="$__unk $__v"
    elif [ "$__sb" = none ] && ! have cryptsetup; then
      warn "$__v: no ext4 filesystem directly on the LV - not checked."
      note "Either it is an encrypted volume (check it from QTS after unlocking it), or the superblock and its first backup copy are damaged. cryptsetup is not on this system to tell the two apart."
      __unk="$__unk $__v"
    elif [ "$__sb" = none ]; then
      warn "$__v: the primary superblock is damaged and e2fsck found no backup copy."
      note "Nothing was changed. A later backup copy can still be intact: [p] and [y] below look for one."
      __bad="$__bad $__v"
    elif [ "$__sb" = backup ]; then
      warn "$__v: the primary superblock is damaged, e2fsck used a backup copy: the filesystem needs a repair."
      note "Nothing was changed: the check ran read-only, even if e2fsck printed FILE SYSTEM WAS MODIFIED."
      __bad="$__bad $__v"
    elif [ "$RC" = 0 ]; then
      ok "$__v: the filesystem is clean."
    elif [ $((RC & 12)) = 8 ]; then
      warn "$__v: e2fsck could not finish (rc=$RC)."
      __unk="$__unk $__v"
    else # 4 = errors left; 1 or 2 after a read-only check = e2fsck saw something to change
      warn "$__v: the filesystem has errors (nothing was changed)."
      if grep -qi 'skipping journal recovery' "$LOGDIR/cmd.out"; then
        note "The journal has not been replayed (read-only check): part of these errors can go away once it is - [p] below replays it and repairs what is safe."
      fi
      __bad="$__bad $__v"
    fi
  done
  while [ -n "$__bad" ]; do
    say ""
    say "Filesystem errors on:$__bad"
    say "  [p] repair what is safe (e2fsck -fp); it stops when a decision is needed"
    say "  [y] repair everything, answering yes to every question (e2fsck -fy); damaged files can be removed"
    say "  [s] leave it and run 'Check File System' in Storage & Snapshots after the start"
    if [ -n "$AUTO" ]; then
      warn "The automatic run stops here: this needs a decision. Run step 5 again."
      return 1
    fi
    rd "Choice: "
    case "$ANS" in
      p | P | y | Y)
        __mode=p
        case "$ANS" in y | Y) __mode=y ;; esac
        if [ "$__mode" = y ]; then
          warn "e2fsck -fy changes the filesystem and can remove damaged files and directories."
          ask_word FSCK || continue
        fi
        __left=""
        for __v in $__bad; do
          __dev=$(dev_of "$__v")
          # QTS has built cachedevN on the LV: e2fsck refuses the LV ("is in use"), QTS itself checks cachedevN
          if is_blk "$DEVMAP/cachedev${__v#lv}"; then
            __dev="$DEVMAP/cachedev${__v#lv}"
            say "$__v: QTS has already built cachedev${__v#lv} on it (not mounted) - the repair runs on $__dev."
          fi
          # -fp does not look for a backup superblock on its own: find the one that opens first, then one e2fsck
          if ! sb_find "$__dev"; then
            warn "$__v: no superblock opens, neither the primary nor a backup copy - e2fsck was not run."
            note "Nothing was changed. This volume needs data recovery (QNAP support) or a restore from a backup."
            __left="$__left $__v"
            continue
          fi
          __b=$SB_BLOCK
          if [ -n "$__b" ]; then
            say "$__v: the primary superblock is damaged - e2fsck runs with the backup copy at block $__b."
          fi
          e2fsck_one "$__mode" "$__v" "$__b" "$__dev"
          if [ $((RC & 252)) = 0 ]; then
            ok "$__v: filesystem repaired${__b:+ from the backup superblock at block $__b} (e2fsck rc=$RC)."
          else
            warn "$__v: errors remain (e2fsck rc=$RC)."
            __left="$__left $__v"
          fi
        done
        __bad=$__left
        ;;
      s | S)
        FSCK=skip
        save_state
        fs_pause_note
        return 0
        ;;
    esac
  done
  if [ -z "$__unk" ]; then
    FSCK="done"
  else
    warn "Not checked:$__unk - run 'Check File System' in Storage & Snapshots after the start."
    FSCK=skip
  fi
  save_state
  return 0
}

# ==================================================================================================
#  After the start: is everything back, did the kernel complain, and the report
# ==================================================================================================
verify_mounts() { # is every data volume of the pool mounted again? sets VERIFY_MISS; 1 when one is missing
  local __v __n __mp __was
  VERIFY_MISS=""
  lvtab
  : >"$LOGDIR/verify.txt"
  say "Data volumes of $VG/$POOL after the start:"
  for __v in $(fs_volumes); do
    __n=${__v#lv}
    __mp=$(awk -v a="cachedev$__n" '{ d = $1; sub(/.*\//, "", d); if (d == a || d == "ce_" a) { print $2; exit } }' "$F_MOUNTS")
    if [ -n "$__mp" ]; then
      printf '  %s[ OK ]%s %-7s mounted at %s\n' "$C_G" "$C_0" "$__v" "$__mp"
      printf '  %-7s mounted at %s\n' "$__v" "$__mp" >>"$LOGDIR/verify.txt"
    else
      printf '  %s[MISS]%s %-7s not mounted\n' "$C_R" "$C_0" "$__v"
      printf '  %-7s NOT mounted\n' "$__v" >>"$LOGDIR/verify.txt"
      VERIFY_MISS="$VERIFY_MISS $__v"
    fi
  done
  if [ -s "$LOGDIR/before.mounts" ]; then
    for __was in $(cat "$LOGDIR/before.mounts"); do
      if ! grep -q " $__was " "$F_MOUNTS"; then
        printf '  %s[info]%s was mounted before, is not now: %s\n' "$C_D" "$C_0" "$__was"
        printf '  was mounted before, is not now: %s\n' "$__was" >>"$LOGDIR/verify.txt"
      fi
    done
  fi
  cat "$LOGDIR/verify.txt" 2>/dev/null >>"$LOG"
  [ -z "$VERIFY_MISS" ]
}

new_kernel_errors() { # storage error lines that appeared in the kernel log since the pool was brought up
  local __n
  if [ ! -s "$LOGDIR/dmesg.pre-start" ]; then return 0; fi
  dmesg 2>/dev/null | awk 'NR == FNR { s[$0] = 1; next } !($0 in s)' "$LOGDIR/dmesg.pre-start" - |
    grep -iE 'device-mapper: .*(error|fail|corrupt|needs_check|read-only)|EXT4-fs (error|warning)|I/O error|Buffer I/O|JBD2: .*error' \
      2>/dev/null >"$LOGDIR/dmesg.new-errors"
  __n=$(grep -c . "$LOGDIR/dmesg.new-errors" 2>/dev/null)
  if [ "${__n:-0}" -gt 0 ]; then
    warn "$__n new kernel message(s) about the storage since the pool was brought up:"
    tail -n 12 "$LOGDIR/dmesg.new-errors"
    cat "$LOGDIR/dmesg.new-errors" 2>/dev/null >>"$LOG"
  else
    ok "No new storage errors in the kernel log since the pool was brought up."
  fi
}

make_report() { # a one-page summary of the session for the ticket or the customer; the path lands in REPORT_FILE
  local __f __tcf __tcl __ranges
  if [ -n "$WORKDIR" ] && [ -d "$WORKDIR" ]; then __f="$WORKDIR/report.txt"; else __f="$LOGDIR/report.txt"; fi
  __tcf="$LOGDIR/$DIAG_TC"
  __tcl="thin_check that gave this result"
  if [ -z "$DIAG_TC" ] || [ ! -f "$__tcf" ]; then # a session of an older version, or that log is gone
    __tcf=$(ls -tr "$LOGDIR"/thin_check-original-*.log 2>/dev/null | head -n 1)
    __tcl="first thin_check of the original metadata"
  fi
  if [ -z "$HEALTH_DONE" ]; then health_check; fi # after a restart of the script: HEALTH_* are not in the session state
  __ranges=""
  if [ -n "$__tcf" ]; then
    __ranges=$(sed -n 's/.*is missing mappings \[\([0-9]*\), *\([0-9]*\)\].*/\1 \2/p' "$__tcf" |
      awk '{ n++; b += $2 - $1 } END { if (n) printf "%d range(s), about %d block(s) of the pool", n, b }')
  fi
  {
    printf 'QNAP pool repair - session report\n=================================\n'
    printf 'Generated:  %s  (tool version %s)\n' "$(ts)" "$VERSION"
    printf 'NAS:        %s, host %s, kernel %s\n' "${MODEL:-?}" "${HOST:-?}" "${KVER:-?}"
    printf 'Pool:       %s/%s, metadata LV %s (%s MiB), scratch LV %s\n' "$VG" "$POOL" "$META" "$META_MB" "${TMPLV:-none}"
    printf 'RAID:       %s\n' "$RAID_SUM"
    printf 'Session:    started %s, stage: %s\n' "${STARTED:-?}" "$(stage_desc "$STAGE")"
    printf '\nDiagnosis\n'
    printf '  result:            %s (%s)\n' "${CLASS:-none}" "$(class_desc "$CLASS")"
    printf '  repair path:       %s\n' "${RPATH:--}"
    printf '  affected volumes:  %s\n' "${AFFECTED:-none named by thin_check}"
    printf '  lost mappings:     %s\n' "${__ranges:-none reported}"
    if [ -n "$__tcf" ]; then
      printf '  %s (%s):\n' "$__tcl" "${__tcf##*/}"
      head -n 30 "$__tcf" | sed 's/^/    | /'
    fi
    printf '\nHardware under the pool\n'
    printf '  kernel log: memory error lines %s, disk I/O error lines %s, out-of-memory lines %s\n' \
      "${HEALTH_MEM:-not checked}" "${HEALTH_IO:-not checked}" "${HEALTH_OOM:-not checked}"
    printf '  RAID members with bad blocks:%s\n' "${HEALTH_BB:- none recorded}"
    printf '\nWhat was done (commands that write or start something: time | exit code | duration | where | command)\n'
    grep -E 'thin_repair|thin_restore|thin_rebuild|thin_patch|vgcfgrestore|vgextend|lvchange -k|dd if=|gz_restore|dd_gzip|e2fsck|storage_util|init_lvm|services\.sh|qsnapman\.sh' \
      "$CMDLOG" 2>/dev/null | sed 's/^/  /'
    printf '\nBackup\n'
    printf '  metadata image:    %s\n' "${BACKUP_FILE:-none}"
    printf '  LVM configuration: %s\n' "$(find_origin || echo none)"
    printf '\nResult\n'
    if stage_ge final_ok; then
      printf '  pool metadata:     repaired, thin_check reports no errors\n'
    else
      printf '  pool metadata:     NOT repaired (stage: %s)\n' "$(stage_desc "$STAGE")"
    fi
    case "$FSCK" in
      done) printf '  filesystem check:  done before the first read-write mount (e2fsck-*.log in the logs)\n' ;;
      skip) printf '  filesystem check:  NOT done\n' ;;
      *) printf '  filesystem check:  not needed for this diagnosis / not run\n' ;;
    esac
    if [ -s "$LOGDIR/verify.txt" ]; then
      printf '  volumes after the start:\n'
      sed 's/^/  /' "$LOGDIR/verify.txt"
    fi
    if [ -s "$LOGDIR/dmesg.new-errors" ]; then
      printf '  new kernel messages about the storage after the start: %s line(s)\n' "$(grep -c . "$LOGDIR/dmesg.new-errors")"
    fi
    printf '\nStill to do\n'
    case "$CLASS" in
      MAPPING | SUPERBLOCK | UNKNOWN)
        if [ "$FSCK" != "done" ]; then
          printf '  - Check File System on the affected volumes (Storage & Snapshots) before trusting the data\n'
        fi
        printf '  - blocks in the lost ranges read as empty: verify the important files, restore them from a backup\n'
        printf '  - snapshots that share the lost ranges are affected as well\n'
        ;;
    esac
    if [ -n "$CLASS" ] && [ "$CLASS" != CLEAN ]; then
      printf '  - find the cause: RAM test (MemHound), SMART of the disks, the RAID state, power\n'
    fi
    if [ "$SERVICES_STOPPED" = 1 ] || [ "$QSNAP_STOPPED" = 1 ]; then
      printf '  - services stopped by the tool are still down: step 5 or a NAS reboot starts them\n'
    fi
    if [ -n "$BACKUP_FILE" ]; then
      printf '  - keep the metadata image until the data has been verified: %s\n' "$BACKUP_FILE"
    fi
    printf '\nCommands that changed the system (in order, with the exit code and the way back at that point):\n'
    if [ -s "$LOGDIR/changes.log" ]; then
      awk -F' [|] ' 'NF >= 4 {u = $4; sub(/^undo: /, "", u); printf "  %s  %s  %s\n      undo: %s\n", $1, $2, $3, u}' \
        "$LOGDIR/changes.log"
    else
      printf '  none\n'
    fi
  } >"$__f" 2>/dev/null
  REPORT_FILE=$__f
  ok "Report: $__f"
}

# ==================================================================================================
#  Viewers: pager, coloured diff, command history
#    Read-only screens, kept apart from the repair code. QTS has no stty, so there is no single-key
#    input and no way to ask the terminal for its size from a script: everything is a letter plus
#    Enter, and the size comes from COLUMNS/LINES (bash keeps them current) or tput, else 80x24.
# ==================================================================================================
rdq() { # like rd, but the answer is not written to the log (pager navigation)
  printf '%s' "$1"
  if ! IFS= read -r ANS; then
    printf '\n'
    safe_exit 3
  fi
}

term_size() { # sets COLS and ROWS
  COLS=${COLUMNS:-}
  ROWS=${LINES:-}
  if [ -z "$COLS" ] && [ -n "$IS_TTY" ] && have tput; then
    COLS=$(tput cols 2>/dev/null)
    ROWS=$(tput lines 2>/dev/null)
  fi
  case "$COLS" in '' | *[!0-9]*) COLS=80 ;; esac
  case "$ROWS" in '' | *[!0-9]*) ROWS=24 ;; esac
}

# pager <file> [title] [plain copy for less]: page through a file
pager() {
  local __f=$1 __total __top=1 __rows __end __pat="" __n
  if [ ! -s "$__f" ]; then
    say "(nothing to show)"
    return 0
  fi
  __total=$(wc -l <"$__f")
  __total=$((__total + 0))
  while :; do
    term_size
    __rows=$((ROWS - 4))
    if [ "$__rows" -lt 5 ]; then __rows=5; fi
    __end=$((__top + __rows - 1))
    if [ "$__end" -gt "$__total" ]; then __end=$__total; fi
    printf '%s--- %s  (lines %s-%s of %s)%s\n' "$C_B" "${2:-$__f}" "$__top" "$__end" "$__total" "$C_0"
    sed -n "${__top},${__end}p" "$__f"
    rdq "${C_D}[Enter] next  [p] back  [g] top  [G] end  [number] go to line  [/text] find  [n] find next  [l] less  [q] quit:${C_0} "
    case "$ANS" in
      q | Q) return 0 ;;
      '')
        if [ "$__end" -ge "$__total" ]; then return 0; fi
        __top=$((__end + 1))
        ;;
      p | P)
        __top=$((__top - __rows))
        if [ "$__top" -lt 1 ]; then __top=1; fi
        ;;
      g) __top=1 ;;
      G)
        __top=$((__total - __rows + 1))
        if [ "$__top" -lt 1 ]; then __top=1; fi
        ;;
      l | L)
        if [ -n "$IS_TTY" ] && have less; then
          less "${3:-$__f}"
        else
          say "less is not available here."
        fi
        ;;
      n | N | /*)
        case "$ANS" in /*) __pat=${ANS#/} ;; esac
        if [ -z "$__pat" ]; then continue; fi
        __n=$(awk -v s="$__top" -v p="$__pat" 'NR > s && index($0, p) { print NR; exit }' "$__f")
        if [ -n "$__n" ]; then __top=$__n; else say "Not found below line $__top: $__pat"; fi
        ;;
      *[!0-9]*) ;;
      *)
        __top=$ANS
        if [ "$__top" -lt 1 ]; then __top=1; fi
        if [ "$__top" -gt "$__total" ]; then __top=$__total; fi
        ;;
    esac
  done
}

diff_color() { # diff_color <unified diff> <label A> <label B>: removed lines red, added lines green
  awk -v R="$C_R" -v G="$C_G" -v C="$C_B" -v Z="$C_0" -v la="$2" -v lb="$3" '
    NR == 1 && /^---/ { printf "%s--- %s%s\n", R, la, Z; next }
    NR == 2 && /^\+\+\+/ { printf "%s+++ %s%s\n", G, lb, Z; next }
    /^@@/ { print C $0 Z; next }
    /^-/ { print R $0 Z; next }
    /^\+/ { print G $0 Z; next }
    { print }
  ' "$1"
}

# diff_side <unified diff> <columns> <label A> <label B>: two panels; the middle column says what a row is:
#   |  same on both sides    ~  changed    <  only on the left (removed)    >  only on the right (added)
diff_side() {
  awk -v R="$C_R" -v G="$C_G" -v C="$C_B" -v Z="$C_0" -v W="$2" -v la="$3" -v lb="$4" '
    function cut(s, n) {
      gsub(/\t/, "    ", s)
      if (length(s) > n) return substr(s, 1, n - 1) ">"
      return s
    }
    function row(l, r, m, cl, cr) {
      printf "%s%s%s %s %s%s%s\n", cl, sprintf("%-" w "s", cut(l, w)), (cl != "" ? Z : ""), m, cr, cut(r, w), (cr != "" ? Z : "")
    }
    function flush(   i, k) {
      k = (nd > na) ? nd : na
      for (i = 1; i <= k; i++) {
        if (i <= nd && i <= na) row(del[i], add[i], "~", R, G)
        else if (i <= nd) row(del[i], "", "<", R, "")
        else row("", add[i], ">", "", G)
      }
      nd = 0; na = 0
    }
    BEGIN {
      w = int((W - 3) / 2); if (w < 20) w = 20
      row(la, lb, "|", C, C)
    }
    NR <= 2 && /^(---|\+\+\+)/ { next }
    /^@@/ { flush(); printf "%s%s%s\n", C, $0, Z; next }
    /^-/ { if (na > 0) flush(); del[++nd] = substr($0, 2); next }
    /^\+/ { add[++na] = substr($0, 2); next }
    { flush(); row(substr($0, 2), substr($0, 2), "|", "", "") }
    END { flush() }
  ' "$1"
}

diff_view() { # diff_view <file A> <file B> <label A> <label B>
  local __a=$1 __b=$2 __la=$3 __lb=$4 __mode=u __w
  if [ ! -r "$__a" ] || [ ! -r "$__b" ]; then
    err "Cannot read $__a or $__b."
    return 1
  fi
  diff -U 3 "$__a" "$__b" 2>/dev/null >"$LOGDIR/view.diff"
  case $? in
    0)
      ok "No difference between: $__la / $__lb"
      return 0
      ;;
    1) ;;
    *)
      err "diff failed on these files."
      return 1
      ;;
  esac
  while :; do
    term_size
    if [ "$__mode" = s ]; then
      diff_side "$LOGDIR/view.diff" "$COLS" "$__la" "$__lb" >"$LOGDIR/view.txt"
    else
      diff_color "$LOGDIR/view.diff" "$__la" "$__lb" >"$LOGDIR/view.txt"
    fi
    pager "$LOGDIR/view.txt" "$__la  ->  $__lb" "$LOGDIR/view.diff"
    rdq "  [u] unified   [s] side by side ($COLS columns)   [w N] set the width to N columns   [Enter] back: "
    case "$ANS" in
      s | S) __mode=s ;;
      u | U) __mode=u ;;
      w\ *)
        __w=${ANS#w }
        case "$__w" in '' | *[!0-9]*) ;; *) COLUMNS=$__w ;; esac
        ;;
      *) return 0 ;;
    esac
  done
}

# hist_index: one line per command of the session log: "<first line>|<last line>|<rc>|<time>|<duration>|<command>"
hist_index() {
  awk '
    /^\[[0-9-]+ [0-9:]+\] \[[0-9]+\] \(.*\) \$ / {
      n++; hl[n] = NR; tl[n] = NR; tm[n] = substr($0, 13, 8); rc[n] = "?"; du[n] = ""
      c = $0; sub(/^\[[0-9-]+ [0-9:]+\] \[[0-9]+\] \([^)]*\) \$ /, "", c); cm[n] = c; cur = n
      next
    }
    cur && /^\[[0-9-]+ [0-9:]+\] \[[0-9]+\] rc=[0-9]+/ {
      s = $0; sub(/^.*\] rc=/, "", s); split(s, p, " ")
      rc[cur] = p[1]; du[cur] = p[2]; tl[cur] = NR; cur = 0
    }
    END { for (i = 1; i <= n; i++) printf "%d|%d|%s|%s|%s|%s\n", hl[i], tl[i], rc[i], tm[i], du[i], cm[i] }
  ' "$LOG" 2>/dev/null
}

hist_list() { # hist_list <index file> [failed]: the index as a table, non-zero exit codes in red
  awk -F'|' -v R="$C_R" -v G="$C_G" -v Z="$C_0" -v only="$2" '{
    c = $6; for (i = 7; i <= NF; i++) c = c "|" $i
    if (only != "" && $3 == "0") next
    printf "%4d  %s  %src=%-3s%s %-10s %s\n", NR, $4, ($3 == "0" ? G : R), $3, Z, $5, substr(c, 1, 120)
  }' "$1"
}

hist_view() {
  local __idx="$LOGDIR/view.idx" __n __line __a __b
  hist_index >"$__idx"
  __n=$(grep -c . "$__idx" 2>/dev/null)
  if [ "${__n:-0}" = 0 ]; then
    say "No commands in the session log yet."
    return 0
  fi
  hist_list "$__idx" >"$LOGDIR/view.txt"
  while :; do
    pager "$LOGDIR/view.txt" "Command history: $__n commands, red = non-zero exit code"
    rdq "Number of a command to read its output   [f] failed only   [a] all   [Enter] back: "
    case "$ANS" in
      '') return 0 ;;
      f | F) hist_list "$__idx" failed >"$LOGDIR/view.txt" ;;
      a | A) hist_list "$__idx" >"$LOGDIR/view.txt" ;;
      *[!0-9]*) ;;
      *)
        __line=$(sed -n "${ANS}p" "$__idx")
        if [ -n "$__line" ]; then
          __a=${__line%%|*}
          __b=${__line#*|}
          __b=${__b%%|*}
          sed -n "${__a},${__b}p" "$LOG" >"$LOGDIR/view.cmd"
          pager "$LOGDIR/view.cmd" "Command $ANS"
        fi
        ;;
    esac
  done
}

dump_section() { # dump_section <state dump> <regex of the section title line>: print that section
  awk -v t="$2" '/^----- / { on = ($0 ~ t); next } on' "$1"
}

pick_log() { # pick_log <glob in the log directory> -> PICK = the chosen file; 1 = none / cancelled
  PICK_LIST=$(ls -t "$LOGDIR"/$1 2>/dev/null)
  if [ -z "$PICK_LIST" ]; then
    say "No such files yet."
    return 1
  fi
  pick "Which file"
}

compare_menu() {
  local __a __b __first __last __x
  PICK_LIST="thin_check: the original metadata against the result of the repair
LVM configuration: the original against the temporary one of the test mount
LVM volumes (lvs -a): the first state dump against the latest
mounts: the first state dump against the latest
any two files of the log directory"
  pick "Compare" || return 0
  case "$PICK" in
    thin_check*)
      __a=$(ls -tr "$LOGDIR"/thin_check-original-*.log 2>/dev/null | head -n 1)
      __b=$(ls -t "$LOGDIR"/thin_check-final-*.log "$LOGDIR"/thin_check-copy*.log 2>/dev/null | head -n 1)
      if [ -z "$__a" ] || [ -z "$__b" ]; then
        say "Both checks are needed: the original (step 1) and the copy or the final result (step 4)."
        return 0
      fi
      diff_view "$__a" "$__b" "original metadata" "after the repair"
      ;;
    "LVM configuration"*)
      __a="$WORKDIR/vg.lvm.origin"
      __b="$WORKDIR/vg.lvm.swapped"
      if [ ! -s "$__a" ] || [ ! -s "$__b" ]; then
        say "No such pair yet: it exists after the test mount of the full path."
        return 0
      fi
      diff_view "$__a" "$__b" "original" "temporary (test mount)"
      ;;
    "LVM volumes"* | mounts*)
      __first=$(ls -tr "$LOGDIR"/state-*.txt 2>/dev/null | head -n 1)
      __last=$(ls -t "$LOGDIR"/state-*.txt 2>/dev/null | head -n 1)
      if [ -z "$__first" ] || [ "$__first" = "$__last" ]; then
        say "Two state dumps are needed (they are taken before and after every step)."
        return 0
      fi
      case "$PICK" in
        mounts*)
          dump_section "$__first" '^----- cat .*mounts$' >"$LOGDIR/view.a"
          dump_section "$__last" '^----- cat .*mounts$' >"$LOGDIR/view.b"
          ;;
        *)
          dump_section "$__first" '^----- lvs -a$' >"$LOGDIR/view.a"
          dump_section "$__last" '^----- lvs -a$' >"$LOGDIR/view.b"
          ;;
      esac
      diff_view "$LOGDIR/view.a" "$LOGDIR/view.b" "${__first##*/}" "${__last##*/}"
      ;;
    any*)
      PICK_LIST=""
      for __x in "$LOGDIR"/*; do
        case "${__x##*/}" in
          view.*) ;;
          *) PICK_LIST="$PICK_LIST${__x##*/}
" ;;
        esac
      done
      pick "First file (before)" || return 0
      __a="$LOGDIR/$PICK"
      pick "Second file (after)" || return 0
      __b="$LOGDIR/$PICK"
      diff_view "$__a" "$__b" "${__a##*/}" "${__b##*/}"
      ;;
  esac
}

_logs_menu() {
  while :; do
    hdr "Logs and history"
    say "Directory: $LOGDIR"
    cat <<EOF
  h) command history: every command with its exit code; pick one to read its output
  s) session log (the full record: commands, output, answers)
  e) errors and warnings only
  t) thin_check results
  c) compare before and after (coloured; also two panels side by side)
  k) kernel messages (dmesg now)
  r) session report (written to the work directory)
  p) pack the logs into a .tgz (to send)
  0) back
EOF
    say "To scroll the screen itself inside screen: Ctrl+a Esc, then PgUp/PgDn; Esc leaves."
    rd "Choice: "
    case "$ANS" in
      h | H) hist_view ;;
      s | S) pager "$LOG" "session.log" ;;
      e | E)
        grep -nE 'FAIL:|WARN:|\] rc=[1-9]' "$LOG" 2>/dev/null >"$LOGDIR/view.txt"
        pager "$LOGDIR/view.txt" "Errors and warnings (the number is the line in session.log)"
        ;;
      t | T) if pick_log 'thin_check-*.log'; then pager "$PICK" "${PICK##*/}"; fi ;;
      c | C) compare_menu ;;
      k | K)
        dmesg 2>/dev/null >"$LOGDIR/dmesg.now"
        pager "$LOGDIR/dmesg.now" "Kernel messages"
        ;;
      r | R)
        make_report
        pager "$REPORT_FILE" "Session report"
        ;;
      p | P)
        snapshot on-demand
        make_report
        pack_logs
        ;;
      0 | '') return 0 ;;
    esac
  done
}

# ==================================================================================================
#  Detecting the environment
# ==================================================================================================
_detect_pool() {
  local __pools __n
  __pools=$(lvs --noheadings -o vg_name,lv_name,lv_attr,lv_size 2>/dev/null | awk '$3 ~ /^t/ {
      h = substr($3, 9, 1); t = ""
      if (h == "M") t = "  [metadata read-only]"
      else if (h == "F") t = "  [failed]"
      else if (h == "D") t = "  [out of data space]"
      else if (h == "p") t = "  [partial - PV missing]"
      print $1 "/" $2 "   (" $4 ")" t
    }')
  __n=$(printf '%s\n' "$__pools" | grep -c .)
  if [ "$__n" = 0 ]; then
    if [ "$1" != again ] && have pvscan &&
      ask_yn "No thin pool is visible in LVM. Rescan the physical volumes (pvscan --cache) and look again?" y; then
      run pvscan --cache
      run pvs
      detect_pool again
      return $?
    fi
    err "No thin pool found in LVM."
    note "This is below the pool metadata - storage is repaired bottom-up:"
    note "RAID: md_checker ; cat /proc/mdstat ; mdadm -E /dev/sdX3"
    note "DRBD: ls /etc/config/ha/r*.res ; drbdadm up rN ; drbdadm disconnect rN ; drbdadm primary rN --force"
    note "LVM:  pvscan --cache ; pvs ; vgs ; lvs -a   (header copies: /etc/config/lvm/backup, archive)"
    return 1
  fi
  if [ "$__n" = 1 ]; then
    PICK=$__pools
  else
    say "Pools found:"
    PICK_LIST=$__pools
    pick "Which pool to work on" || return 1
  fi
  PICK=${PICK%% *}
  VG=${PICK%%/*}
  POOL=${PICK#*/}
  META="${POOL}_tmeta"
  case "$VG$POOL" in
    *[!A-Za-z0-9_.+-]*)
      err "Unsupported characters in the VG/pool name: $VG/$POOL"
      return 1
      ;;
  esac
  return 0
}

_detect_tmplv() { # detect_tmplv [ask]  - the scratch LV for the repaired metadata copy
  local __sw __cands __n
  lvtab
  # interrupted test mount: the VG holds an <lv>_tmeta that is not the pool's own metadata LV
  __sw=$(printf '%s\n' "$LVTAB" | awk -F'|' -v m="$META" '$1 ~ /_tmeta$/ && $1 != m {print $1; exit}')
  if [ -n "$__sw" ]; then
    TMPLV=${__sw%_tmeta}
    return 0
  fi
  if [ -n "$TMPLV" ] && lv_exists "$TMPLV"; then return 0; fi
  # candidates: only the system-reserved LVs (QLV: lv544-lv799), linear
  __cands=$(printf '%s\n' "$LVTAB" | awk -F'|' -v need="$META_MB" '
    $2 ~ /^-/ && $1 ~ /^lv[0-9]+$/ {
      n = substr($1, 3) + 0
      if (n >= 544 && n <= 799)
        print $1 "   (" int($3) " MiB" ($3 + 0 < need ? ", smaller than the metadata LV" : "") ")"
    }')
  __n=$(printf '%s\n' "$__cands" | grep -c .)
  if [ "$__n" = 1 ] && [ "$1" != ask ]; then
    TMPLV=${__cands%% *}
    return 0
  fi
  if [ -z "$__cands" ]; then
    TMPLV=""
    warn "No scratch LV (system range lv544-lv799) in $VG."
    note "Only the legacy path (thin_dump + thin_restore) will be available."
    return 0
  fi
  say "Scratch LV candidates (the contents will be overwritten!):"
  PICK_LIST=$__cands
  if pick "Scratch LV"; then TMPLV=${PICK%% *}; else TMPLV=""; fi
  return 0
}

reset_state() {
  VG=""
  POOL=""
  META=""
  TMPLV=""
  PDATA=""
  WORKDIR=""
  STAGE="new"
  CLASS=""
  RPATH=""
  SERVICES_STOPPED=""
  QSNAP_STOPPED=""
  BACKUP_FILE=""
  BACKUP_KIND=""
  XML_OK=""
  NOBACKUP=""
  DATA_ACK=""
  AFFECTED=""
  DIAG_TC=""
  FSCK=""
  COPY_LIVE=""
  TIERS_USED=""
  STARTED=""
}

init_session() {
  local __old_vg __old_pool __t
  HOST=$(hostname 2>/dev/null | tr -cd 'A-Za-z0-9_-')
  MODEL=$(getsysinfo model 2>/dev/null)
  FW="$(getcfg System Version -f /etc/config/uLinux.conf 2>/dev/null) $(getcfg System 'Build Number' -f /etc/config/uLinux.conf 2>/dev/null)"
  mkdir -p "$PERSIST" 2>/dev/null
  chmod 700 "$PERSIST" 2>/dev/null
  LOGDIR="$TMPD/$SESSION-logs"
  mkdir -p "$LOGDIR"
  LOG="$LOGDIR/session.log"
  CMDLOG="$LOGDIR/commands.log"
  RCF="$TMPD/$SESSION.rc"
  set_cap
  KVER=$(uname -r 2>/dev/null)
  logf "---- start qnap-pool-repair $VERSION (PID $$) kernel $KVER, uLinux.conf Version $FW ----"

  hdr "QNAP pool repair $VERSION"
  banner warning
  say "This script changes your storage pool's metadata and can damage your data."
  say "Use with caution. When unsure, ask first: forum.qnap.net.pl"
  # the menu is about 20 lines: on an 80x25 screen the warning would be gone before anyone reads it
  if [ -z "$AUTO_START" ]; then enter_wait "Press Enter to continue."; fi

  if have zpool; then
    err "This is QuTS hero (ZFS): there is no LVM thin pool here. The tool handles QTS only."
    safe_exit 1
  fi
  need_check || safe_exit 1

  if [ -s "$PERSIST/state" ] && ! load_state; then
    warn "The saved session file is not valid; it is set aside and a new session starts."
    mv -f "$PERSIST/state" "$PERSIST/state.bad-$(date +%Y%m%d-%H%M%S)" 2>/dev/null
    reset_state
  fi
  if [ -s "$PERSIST/state" ]; then
    if [ "$STAGE" = "done" ] || [ -z "$VG" ]; then
      mv -f "$PERSIST/state" "$PERSIST/state.old-$(date +%Y%m%d-%H%M%S)" 2>/dev/null
      reset_state
    else
      hdr "Unfinished repair session found"
      say "Pool: $VG/$POOL   started: ${STARTED:-?}"
      say "Stage: $(stage_desc "$STAGE")"
      say "Work directory: ${WORKDIR:-none}"
      if ask_yn "Continue this session?" y; then
        VGDM=$(dm_esc "$VG")
        if [ -n "$WORKDIR" ] && [ -d "$WORKDIR/logs" ]; then
          switch_logs "$WORKDIR/logs"
        elif [ -n "$WORKDIR" ]; then
          warn "Work directory $WORKDIR is unavailable (drive unplugged?)."
        fi
        logf "---- session resumed, stage $STAGE ----"
      else
        __old_vg=$VG
        __old_pool=$POOL
        mv -f "$PERSIST/state" "$PERSIST/state.old-$(date +%Y%m%d-%H%M%S)" 2>/dev/null
        reset_state
        say "The old session ($__old_vg/$__old_pool) was archived."
      fi
    fi
  fi

  if [ -z "$VG" ]; then
    # a new session: the self-test once, on request (never in the automatic run)
    if [ -z "$AUTO_START" ] && ask_yn "Test the commands this script uses first (read-only, a few seconds)?" n; then
      selftest
    fi
    detect_pool || safe_exit 1
    STARTED=$(ts)
    rm -f "$LOGDIR"/bringup.expected "$LOGDIR"/bringup.rows "$LOGDIR"/bringup.rebuilt # a new session: no table of an earlier one in /tmp
  fi
  VGDM=$(dm_esc "$VG")
  lvtab
  if ! lv_exists "$POOL"; then
    err "Pool $VG/$POOL does not exist in LVM."
    safe_exit 1
  fi
  META_MB=$(lv_size_mb "$META")
  META_MB=${META_MB:-0}
  METADEV=$(dev_of "$META")
  detect_tmplv
  if [ -n "$TMPLV" ]; then TMPDEV=$(dev_of "$TMPLV"); fi
  raid_check
  lvm_check

  if is_swapped; then
    warn "LVM is in the TEMPORARY state: pool $POOL points at ${TMPLV}_tmeta."
    if copy_live; then
      copy_live_note
    else
      note "(interrupted test mount) - step 4) Repair finishes the procedure."
      if [ -n "$VG_SKIP" ]; then note "The VG carries the skip-activation flag: the pool stays offline over a reboot until then."; fi
    fi
    if ! stage_ge swapped || stage_ge verified; then STAGE=swapped; fi
  elif [ "$STAGE" = swapped ]; then
    STAGE=tmp_ok
  fi
  if [ "$STAGE" = new ] && ! pool_is_online; then STAGE=offline; fi
  if [ -z "$WORKDIR" ] && [ "$STAGE" != "done" ]; then
    choose_workdir || true
  fi
  logs_home
  save_state
  if [ -n "$DEBUG" ]; then
    trace_on
    if [ -z "$TRACE_ON" ]; then
      say "Debug: call trace and framed commands are on. The full shell trace (trace.log) needs a work directory."
    fi
  fi
  snapshot start
}

# ==================================================================================================
#  Main menu
# ==================================================================================================
steps_bar() { # steps_bar <recommended step>: the five steps and where each one stands
  local __i __s __mark __col __out=""
  for __i in 1 2 3 4 5; do
    __mark=""
    case "$__i" in
      1)
        __s=Diag
        if stage_ge diagnosed; then __mark=ok; fi
        ;;
      2)
        __s=Offline
        if stage_ge final_ok || ! pool_is_online; then __mark=ok; fi
        ;;
      3)
        __s=Backup
        if [ -n "$BACKUP_FILE" ] && [ -s "$BACKUP_FILE" ]; then __mark=ok; fi
        ;;
      4)
        __s=Repair
        if stage_ge final_ok; then __mark=ok; fi
        ;;
      5)
        __s=Start
        if [ "$STAGE" = "done" ]; then __mark=ok; fi
        ;;
    esac
    if [ "$__i" = "$1" ]; then
      __col=$C_Y
      __mark=${__mark:-next}
    elif [ "$__mark" = ok ]; then
      __col=$C_G
    else
      __col=$C_D
      __mark="--"
    fi
    __out="$__out${__out:+ | }${__col}$__i $__s $__mark${C_0}"
  done
  printf '%s' "$__out"
}

recommend() { # number of the recommended step
  if [ -n "$PV_MISSING" ]; then
    echo 6
    return
  fi
  case "$STAGE" in
    new) if pool_is_online; then echo 2; else echo 1; fi ;;
    offline) echo 1 ;;
    diagnosed) if [ "$CLASS" = CLEAN ] && ! flag_odd "$SB_FLAGS"; then echo 5; else echo 3; fi ;;
    swapped) if { [ -z "$VG_SKIP" ] || [ "$COPY_LIVE" = 1 ]; } && pool_is_online; then echo 2; else echo 4; fi ;; # up on the copy: offline first
    backed_up | tmp_ok | verified | final_started) echo 4 ;;
    final_ok) echo 5 ;;
    *) echo 0 ;;
  esac
}

step_name() {
  case "$1" in
    1) echo "Status and diagnosis (thin_check, read-only)" ;;
    2) echo "Prepare: stop the services, unmount, deactivate the VG" ;;
    3) echo "Backup: LVM configuration + metadata image" ;;
    4) case "$STAGE" in
      tmp_ok) if [ "$RPATH" = full ]; then echo "Repair - step B: test mount on the copy"; else echo "Repair - step C: write to $META"; fi ;;
      swapped) echo "Repair - step B: finish the test and restore LVM" ;;
      verified) echo "Repair - step C: write to $META" ;;
      final_started) echo "Repair - RETRY the interrupted write to $META" ;;
      *) echo "Repair the metadata" ;;
    esac ;;
    5) echo "Bring the pool and the volumes up" ;;
    6) echo "Tools -> i) restore the PV in missing mode" ;;
    0) echo "Exit" ;;
  esac
}

step_short() { # the step's name in one word, for the menu's recommended line
  case "$1" in
    1) echo "Diagnosis" ;;
    2) echo "Offline" ;;
    3) echo "Backup" ;;
    4) echo "Repair" ;;
    5) echo "Start" ;;
    *) step_name "$1" ;;
  esac
}

# The end banner of a step that returned non-zero: step 4 or 5 from the menu, any step of the automatic run
# (shown once, at the run's end). A step that printed no err line was stopped by an answer of the operator;
# that is not a failure and gets no banner. FAILED or CRITICAL is decided from the state after the step, never
# from the message text: CRITICAL when the original metadata is half written, when the live metadata sits on
# the working copy with LVM still swapped, or when step 5 leaves the pool down or without a mounted volume.
fail_banner() { # fail_banner <step>
  local __k=failed
  if [ -z "$LAST_ERR" ]; then return 0; fi
  if [ "$STAGE" = final_started ] || { [ "$COPY_LIVE" = 1 ] && is_swapped; }; then
    __k=critical
  elif [ "$1" = 5 ]; then
    if pool_is_online; then
      compute_stack
      if [ -z "$ST_MPS" ]; then __k=critical; fi
    else
      __k=critical
    fi
  fi
  banner "$__k" "$LAST_ERR"
  chg_summary
  END_WAIT=1
}

# Steps 1-5 in a row. Questions that have a safe default are answered with it and shown as [auto];
# the operator is still asked about busy volumes, the data on the test mount and the typed YES
# before the original metadata is written. Any failure, and anything that needs a decision, ends the run.
_auto_run() {
  local __rec __last="" __fail=""
  hdr "Automatic run"
  say "The recommended steps run one after another. Questions with a safe default take it ([auto])."
  say "You are still asked for: busy volumes, the data check on the test mount, and the typed YES before the original metadata is written. Any failure ends the run."
  need_workdir || {
    err "The automatic run needs a work directory."
    return 1
  }
  ask_yn "Start?" y || return 1
  AUTO=1
  while :; do
    lvm_check
    __rec=$(recommend)
    case "$__rec" in
      0)
        ok "Nothing left to do."
        break
        ;;
      6)
        warn "A PV is in missing mode - that needs a decision: 6) Tools -> i."
        break
        ;;
    esac
    if [ "$__rec:$STAGE" = "$__last" ]; then
      warn "Step $__rec did not move the session forward - back to the menu."
      break
    fi
    __last="$__rec:$STAGE"
    say ""
    say ">>> automatic run - step $__rec: $(step_name "$__rec")"
    LAST_ERR=""
    case "$__rec" in
      1) do_diag ;;
      2) do_prepare ;;
      3) do_backup ;;
      4) do_repair ;;
      5) do_startup ;;
    esac || {
      warn "Step $__rec stopped - the automatic run ends here."
      __fail=$__rec
      break
    }
    if [ -n "$TERM_REQ" ]; then break; fi
  done
  AUTO=""
  if [ -n "$__fail" ]; then fail_banner "$__fail"; fi
  return 0
}

main_menu() {
  local __rec __i __h __a __c __t
  while :; do
    if [ -n "$END_WAIT" ]; then # the menu must not push an end banner off an 80x25 screen before it is read
      END_WAIT=""
      enter_wait "Press Enter to return to the menu."
    fi
    lvm_check
    __rec=$(recommend)
    __h=$(pool_health)
    # An 80x25 screen: no line over 79 columns, and 22 lines with the prompt even when both alert lines show
    __a=""
    if [ -n "$__h" ]; then __a="${C_Y}Pool health: $__h$C_0"; fi
    if [ -n "$PV_MISSING" ]; then __a="$__a${__a:+   }${C_R}LVM: PV in missing mode: $(fit 28 "$(echo $PV_MISSING)")$C_0"; fi
    __c=""
    case "$CACHE_MODE" in
      rw) __c="SSD cache read-write" ;;
      ro) __c="SSD cache read-only" ;;
      *) if [ -n "$LVM_CACHE" ]; then __c="SSD cache layer"; fi ;;
    esac
    if [ "${TIERS_USED:-0}" -ge 2 ]; then
      if [ -n "$__c" ]; then __c="$__c, Qtier ($TIERS_USED tiers)"; else __c="Qtier in use ($TIERS_USED tiers)"; fi
      __c="$C_R$__c - repair escalates to QNAP support$C_0"
    else
      case "$__c" in
        *read-write) __c="${C_R}LVM: $__c - repair escalates to QNAP support$C_0" ;;
        *read-only) __c="LVM: $__c - the repair asks whether it is removed or disabled" ;;
        ?*) __c="LVM: $__c (cache_client / fcorig)" ;;
      esac
    fi
    if [ -z "$__a" ] || [ -z "$__c" ]; then printf '\n'; fi
    __t="=== QNAP pool repair $VERSION | ${MODEL:-NAS} | kernel ${KVER:-?} | ${HOST:-?}${ALLOW_NO_BACKUP:+ | --allow-no-backup}"
    printf '%s%s%s\n' "$C_B" "$(fit 74 "$__t" | awk '{ $0 = $0 " "; while (length($0) < 78) $0 = $0 "="; print }')" "$C_0"
    fit 79 " Pool: $VG/$POOL   metadata: $META ($META_MB MiB)   scratch LV: ${TMPLV:-NONE}"
    __t=$RAID_SUM
    if [ "${#__t}" -gt 72 ]; then __t="$(printf '%s\n' "$__t" | tr ';' '\n' | grep -c .) arrays under $VG, state: $RAID_STATE (step 1 lists them)"; fi
    printf '\n RAID: %s\n' "$__t"
    if [ -n "$__a" ]; then printf ' %s\n' "$__a"; fi
    if [ -n "$__c" ]; then printf ' %s\n' "$__c"; fi
    printf ' Work directory: %s\n' "$(fit 62 "${WORKDIR:-NONE (diagnosis only)}")"
    printf ' Diagnosis: %s%s   Tool: %s\n' "${CLASS:--}" "${CLASS:+ ($(class_desc "$CLASS"))}" "$(fit 27 "${PDATA:-(detected at diagnosis)}")"
    printf ' Stage: %s%s%s   Path: %s\n' "$C_Y" "$(stage_desc "$STAGE")" "$C_0" "${RPATH:--}"
    printf ' Steps: %s\n' "$(steps_bar "$__rec")"
    printf '%s------------------------------------------------------------------------------%s\n' "$C_B" "$C_0"
    printf ' %s[Enter] recommended step: %s) %s%s\n' "$C_G" "$__rec" "$(step_short "$__rec")" "$C_0"
    printf '  a) Automatic run: the remaining steps; stops for decisions and before a write\n'
    for __i in 1 2 3 4 5; do printf '  %s) %s\n' "$__i" "$(step_name "$__i")"; done
    printf '  6) Tools (tp_collect, undo the LVM swap, restore the backup...)\n'
    printf '  7) Logs and history (command history, pager, before/after diff, report)\n'
    printf '  8) Debug mode: %s (call trace, framed commands, shell trace in trace.log)\n' "$(if [ -n "$DEBUG" ]; then echo ON; else echo off; fi)"
    printf '  0) Exit\n'
    rd "Choice: "
    if [ -z "$ANS" ]; then ANS=$__rec; fi
    case "$ANS" in
      a | A) auto_run ;;
      1) do_diag ;;
      2) do_prepare ;;
      3) do_backup ;;
      4)
        LAST_ERR=""
        do_repair || fail_banner 4
        ;;
      5)
        LAST_ERR=""
        do_startup || fail_banner 5
        ;;
      6) tools_menu ;;
      7) logs_menu ;;
      8) if [ -n "$DEBUG" ]; then
        trace_off
        DEBUG=""
        say "Debug mode off."
      else
        DEBUG=1
        trace_on
        say "Debug mode on.${OUT_CAP:+ The shell trace file needs a work directory.}"
      fi ;;
      0) do_exit ;;
      *) continue ;;
    esac
    if [ -n "$TERM_REQ" ]; then
      say "SIGTERM received - stopping after the current step."
      safe_exit 4
    fi
  done
}

do_exit() {
  local __why=""
  if is_swapped; then
    warn "LVM is in the TEMPORARY state (pool -> ${TMPLV}_tmeta)!"
    if copy_live; then
      copy_live_note
    elif [ -n "$VG_SKIP" ]; then
      note "The VG carries the skip-activation flag: after a reboot the pool stays offline until"
      note "step 4) Repair is finished or the swap is undone (6) Tools -> c)."
    else
      note "Undo the swap before leaving: 6) Tools -> c. Otherwise the pool comes up on the"
      note "working copy instead of the real $META after a reboot."
    fi
    ask_yn "Exit anyway?" n || return 0
    __why="LVM is still in the temporary state: pool $POOL points at ${TMPLV}_tmeta."
  elif [ "$STAGE" = final_started ]; then
    warn "The write to $META was not completed - the pool will not come up correctly."
    ask_yn "Exit anyway?" n || return 0
    __why="The write to $META was not completed."
  elif [ "$COPY_LIVE" = 1 ]; then
    copy_live_note
    note "A reboot before step 4) Repair has finished starts the pool on the out-of-date original."
    ask_yn "Exit anyway?" n || return 0
    __why="The working copy ($TMPLV) holds the live metadata; the original $META is out of date."
  fi
  if [ -n "$__why" ]; then
    banner critical "$__why"
    chg_summary
  fi
  if [ "$SERVICES_STOPPED" = 1 ] && [ -n "$VG_SKIP" ] && ! is_swapped; then
    warn "The VG carries the skip-activation flag: after a reboot the pool and the apps on it stay down until step 5."
  elif [ "$SERVICES_STOPPED" = 1 ]; then
    warn "The QTS services are stopped (step 5 starts them again; a NAS reboot does too)."
  elif [ "$QSNAP_STOPPED" = 1 ]; then
    warn "The snapshot manager is stopped (step 5 starts it again; a NAS reboot does too)."
  fi
  save_state
  say "Logs: $LOGDIR"
  if [ "$STAGE" != "done" ]; then say "The session can be resumed: run the script again."; fi
  safe_exit 0
}

# ==================================================================================================
#  Start-up: copy to /tmp, screen session
# ==================================================================================================
usage() {
  cat <<EOF
qnap-pool-repair $VERSION - interactive repair of thin pool metadata (QNAP QTS)

Usage:  sh qnap-pool-repair.sh [--no-screen] [--debug] [--auto] [--allow-no-backup] [--selftest]

  --no-screen   do not start inside a screen session
  --selftest    check the commands this script uses (read-only) and exit
  --debug       call trace on the screen, framed commands, full shell trace in trace.log
  --auto        start the automatic run (steps 1-5 in a row) after the detection
  --allow-no-backup  emergency only: lets the staged path be confirmed without a metadata image
  --help        this help
  --version     version

The script detects the VG, the pool, the scratch LV, the RAID array and pdata_tools (8192/4096).
Menu: 1 diagnosis -> 2 prepare (offline) -> 3 backup -> 4 repair -> 5 bring the pool up.
[Enter] in the menu runs the recommended next step. A session can be interrupted and resumed.
EOF
}

# The terminfo entries of the "QNAP Support Screenfix v2" script, as it carried them: base64 of the compiled files.
terminfo_data() { # terminfo_data <name>: one entry as base64 text
  case "$1" in
    xterm)
      cat <<'__EOF_xterm__'
GgEwAA8AAwBkATwCeHRlcm18eHRlcm0gdGVybWluYWwgZW11bGF0b3IgKFggV2luZG93IFN5c3Rl
bSkAAAEAAAEAAAABAAAAAAEBAFAACAAYAP//AAACAAQAFQAaACIAJgD/////KgA7AD0A//9BAP//
//9DAP//RwD//0sATwD/////UwD//1UAWgD/////YwD/////aABtAHIA//93AHkAfQD//4oAjwCT
AP//////////lwD///////+4AP//vAD///////++AP//wwD//////////8cAywDRANUA2QDdAOMA
6QDvAPUA+wAAAf//BQH//wkBDgETAf///////xcBGwEjAf//////////////////////////////
/////////ysBNAE9Af////9GAU8BWAH//2EB/////////////////////2oB/////4sB//+OAZEB
kwH///////+WAf////////////////////////////+YAf/////////////////////NAf//////
///////////////RAf/////WAf//////////////////////////////////////////////////
////////////////2wH/////////////////////////////////////////////////////////
/+AB5gHsAfIB+AH+AQQCCgIQAhYC////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////8cAicCLAI0Av//////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////OAIHAA0A
G1slaSVwMSVkOyVwMiVkcgAbWzNnABtbSBtbMkoAG1tLABtbSgAbWyVpJXAxJWQ7JXAyJWRIAAoA
G1tIAAgAG1tDABtbQQAbW1AAG1tNAA4AG1sxbQAbNxtbPzQ3aAAbWzRoABtbN20AG1s3bQAbWzRt
AA8AG1ttABtbMkobWz80N2wbOAAbWzRsABtbbQAbW20AGzcbW3IbW20bWz83aBtbPzE7Mzs0OzZs
G1s0bBs4Gz4AG1tMAAgAG1szfgAbT0IAG09QABtbMjF+ABtPUQAbT1IAG09TABtbMTV+ABtbMTd+
ABtbMTh+ABtbMTl+ABtbMjB+ABtbMX4AG1syfgAbT0QAG1s2fgAbWzV+ABtPQwAbT0EAG1s/MWwb
PgAbWz8xaBs9ABtbJXAxJWRQABtbJXAxJWRNABtbJXAxJWRCABtbJXAxJWRMABtbJXAxJWREABtb
JXAxJWRDABtbJXAxJWRBABs3G1tyG1ttG1s/N2gbWz8xOzM7NDs2bBtbNGwbOBs+ABs4ABs3AAoA
G00ACQBgYGFhZmZnZ2lpampra2xsbW1ubm9vcHBxcXJyc3N0dHV1dnZ3d3h4eXl6ent7fHx9fX5+
ABspMAAbWzR+ABtbMX4AG1s0fgAbWzIzfgAbWzI0fgAbWzI1fgAbWzI2fgAbWzI4fgAbWzI5fgAb
WzMxfgAbWzMyfgAbWzMzfgAbWzM0fgAbWyVpJWQ7JWRSABtbNm4AG1s/MTsyYwAbW2MAG1tNAA==
__EOF_xterm__
      ;;
    xterm-color)
      cat <<'__EOF_xterm-color__'
GgEnACYAEACdAVsCeHRlcm0tY29sb3J8bnh0ZXJtfGdlbmVyaWMgY29sb3IgeHRl
cm0AAAEAAAEAAAABAAAAAAEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAUAAIABgA
//////////////////////////8IAEAA/v///wAAAgAEABUAGgAiACYA/////yoA
OwA9AP//QQD/////QwD//0cA//9LAE8A/////1MA//9VAFoA/////2MA/////2gA
bQByAP//dwB5AH0A//+KAI8AkwD//////////5cA////////uAD//7wA////////
vgD//8MA///////////HAM0A0wDZAN8A5QDrAPEA9wD9AP//AwH//wgB//8MAREB
FgH///////8aAR4BJgH///////////////////////////////////////8uATcB
QAH/////SQFSAVsB//9kAf////////////////////9tAf////+OAf//kQGUAZYB
//+ZAf//nAH/////////////////////////////ngH/////////////////////
0wH/////////////////////////////1wH/////////////////////////////
/////////////////////////////////////9wB////////////////////////
///////////////////////////////////hAecB7QHzAfkB/wEFAgsCEQIXAv//
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////HQIoAi0CNQI5Av//
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
/////////////////////z0C////////QQJLAv//////////////////////////
////////////////////////////////////////////////////////////////
//////////////////////////////////////////9VAlgCBwANABtbJWklcDEl
ZDslcDIlZHIAG1szZwAbW0gbWzJKABtbSwAbW0oAG1slaSVwMSVkOyVwMiVkSAAK
ABtbSAAIABtbQwAbW0EAG1tQABtbTQAOABtbMW0AGzcbWz80N2gAG1s0aAAbWzdt
ABtbN20AG1s0bQAPABtbbQAbWzJKG1s/NDdsGzgAG1s0bAAbW20AG1ttABtbbRtb
PzdoG1s0bBs+GzcbW3IbWz8xOzM7NDs2bBs4ABtbTAAIABtbM34AG09CABtbMTF+
ABtbMjF+ABtbMTJ+ABtbMTN+ABtbMTR+ABtbMTV+ABtbMTd+ABtbMTh+ABtbMTl+
ABtbMjB+ABtbMn4AG09EABtbNn4AG1s1fgAbT0MAG09BABtbPzFsGz4AG1s/MWgb
PQAbWyVwMSVkUAAbWyVwMSVkTQAbWyVwMSVkQgAbWyVwMSVkTAAbWyVwMSVkRAAb
WyVwMSVkQwAbWyVwMSVkQQAbW20bWz83aBtbNGwbPhs3G1tyG1s/MTszOzQ7Nmwb
OAAbOAAbNwAKABtNABtIAAkAYGBhYWZmZ2dpaWpqa2tsbG1tbm5vb3BwcXFycnNz
dHR1dXZ2d3d4eHl5enp7e3x8fX1+fgAbKTAAG1sxfgAbWzR+ABtbMjN+ABtbMjR+
ABtbMjV+ABtbMjZ+ABtbMjh+ABtbMjl+ABtbMzF+ABtbMzJ+ABtbMzN+ABtbMzR+
ABtbJWklZDslZFIAG1s2bgAbWz8xOzJjABtbYwAbW20AG1tNABtbMyVwMSVkbQAb
WzQlcDElZG0AG2wAG20A
__EOF_xterm-color__
      ;;
    xterm-256color)
      cat <<'__EOF_xterm-256color__'
GgElACYADwCdATAGeHRlcm0tMjU2Y29sb3J8eHRlcm0gd2l0aCAyNTYgY29sb3Jz
AAABAAABAAAAAQAAAAABAQAAAAAAAAABAAABAAEBAAAAAAAAAAABAFAACAAYAP//
////////////////////////AAH/fwAABAAGAAgAGQAeACYAKgAuAP//OQBKAEwA
UABXAP//WQBmAP//agBuAHgAfAD/////gACEAIkAjgD//6AApQCqAP//rwC0ALkA
vgDHAMsA0gD//+QA6QDvAPUA////////BwH///////8ZAf//HQH///////8fAf//
JAH//////////ygBLAEyATYBOgE+AUQBSgFQAVYBXAFgAf//ZQH//2kBbgFzAXcB
fgH//4UBiQGRAf////////////////////////////+ZAaIB/////6sBtAG9AcYB
zwHYAeEB6gHzAfwB////////BQIJAg4CEwInAjAC/////0ICRQJQAlMCVQJYArUC
//+4Av//////////ugK+AsICxgLKAv/////OAv//AwP/////BwMNA///////////
//////////////////8TAxcD////////////////////////////////////////
//////////////////////////8bA/////8iA///////////KQMwAzcD/////z4D
//9FA////////0wD/////////////1MDWQNfA2YDbQN0A3sDgwOLA5MDmwOjA6sD
swO7A8IDyQPQA9cD3wPnA+8D9wP/AwcEDwQXBB4EJQQsBDMEOwRDBEsEUwRbBGME
awRzBHoEgQSIBI8ElwSfBKcErwS3BL8ExwTPBNYE3QTkBOkE////////////////
///////////////////////////////////////////wBPsEAAUTBRcFIAUnBf//
//////////////////////////+FBf///////////////////////4oF////////
////////////////////////////////////////////////////////////////
////////////////kAX///////+UBdMF//////////////////8TBv//////////
////////////////////////////////////////////////////////////////
/////////////////////////////////////yoGLQYbW1oABwANABtbJWklcDEl
ZDslcDIlZHIAG1szZwAbW0gbWzJKABtbSwAbW0oAG1slaSVwMSVkRwAbWyVpJXAx
JWQ7JXAyJWRIAAoAG1tIABtbPzI1bAAIABtbPzEybBtbPzI1aAAbW0MAG1tBABtb
PzEyOzI1aAAbW1AAG1tNABsoMAAbWzVtABtbMW0AG1s/MTA0OWgbWzIyOzA7MHQA
G1sybQAbWzRoABtbOG0AG1s3bQAbWzdtABtbNG0AG1slcDElZFgAGyhCABsoQhtb
bQAbWz8xMDQ5bBtbMjM7MDswdAAbWzRsABtbMjdtABtbMjRtABtbPzVoJDwxMDAv
PhtbPzVsABtbIXAbWz8zOzRsG1s0bBs+ABtbTAB/ABtbM34AG09CABtPUAAbWzIx
fgAbT1EAG09SABtPUwAbWzE1fgAbWzE3fgAbWzE4fgAbWzE5fgAbWzIwfgAbT0gA
G1syfgAbT0QAG1s2fgAbWzV+ABtPQwAbWzE7MkIAG1sxOzJBABtPQQAbWz8xbBs+
ABtbPzFoGz0AG1s/MTAzNGwAG1s/MTAzNGgAG1slcDElZFAAG1slcDElZE0AG1sl
cDElZEIAG1slcDElZEAAG1slcDElZFMAG1slcDElZEwAG1slcDElZEQAG1slcDEl
ZEMAG1slcDElZFQAG1slcDElZEEAG1tpABtbNGkAG1s1aQAlcDElYxtbJXAyJXsx
fSUtJWRiABtjG10xMDQHABtbIXAbWz8zOzRsG1s0bBs+ABs4ABtbJWklcDElZGQA
GzcACgAbTQAlPyVwOSV0GygwJWUbKEIlOxtbMCU/JXA2JXQ7MSU7JT8lcDUldDsy
JTslPyVwMiV0OzQlOyU/JXAxJXAzJXwldDs3JTslPyVwNCV0OzUlOyU/JXA3JXQ7
OCU7bQAbSAAJABtPdwAbT3kAG091ABtPcQAbT3MAYGBhYWZmZ2dpaWpqa2tsbG1t
bm5vb3BwcXFycnNzdHR1dXZ2d3d4eHl5enp7e3x8fX1+fgAbW1oAG1s/N2gAG1s/
N2wAG09GABtPTQAbWzM7Mn4AG1sxOzJGABtbMTsySAAbWzI7Mn4AG1sxOzJEABtb
NjsyfgAbWzU7Mn4AG1sxOzJDABtbMjN+ABtbMjR+ABtbMTsyUAAbWzE7MlEAG1sx
OzJSABtbMTsyUwAbWzE1OzJ+ABtbMTc7Mn4AG1sxODsyfgAbWzE5OzJ+ABtbMjA7
Mn4AG1syMTsyfgAbWzIzOzJ+ABtbMjQ7Mn4AG1sxOzVQABtbMTs1UQAbWzE7NVIA
G1sxOzVTABtbMTU7NX4AG1sxNzs1fgAbWzE4OzV+ABtbMTk7NX4AG1syMDs1fgAb
WzIxOzV+ABtbMjM7NX4AG1syNDs1fgAbWzE7NlAAG1sxOzZRABtbMTs2UgAbWzE7
NlMAG1sxNTs2fgAbWzE3OzZ+ABtbMTg7Nn4AG1sxOTs2fgAbWzIwOzZ+ABtbMjE7
Nn4AG1syMzs2fgAbWzI0OzZ+ABtbMTszUAAbWzE7M1EAG1sxOzNSABtbMTszUwAb
WzE1OzN+ABtbMTc7M34AG1sxODszfgAbWzE5OzN+ABtbMjA7M34AG1syMTszfgAb
WzIzOzN+ABtbMjQ7M34AG1sxOzRQABtbMTs0UQAbWzE7NFIAG1sxSwAbWz82OWwA
G1slaSVkOyVkUgAbWzZuABtbPyVbOzAxMjM0NTY3ODldYwAbW2MAG1szOTs0OW0A
G10xMDQHABtdNDslcDElZDtyZ2I6JXAyJXsyNTV9JSolezEwMDB9JS8lMi4yWC8l
cDMlezI1NX0lKiV7MTAwMH0lLyUyLjJYLyVwNCV7MjU1fSUqJXsxMDAwfSUvJTIu
MlgbXAAbWzNtABtbMjNtABtbPAAbWyU/JXAxJXs4fSU8JXQzJXAxJWQlZSVwMSV7
MTZ9JTwldDklcDElezh9JS0lZCVlMzg7NTslcDElZCU7bQAbWyU/JXAxJXs4fSU8
JXQ0JXAxJWQlZSVwMSV7MTZ9JTwldDEwJXAxJXs4fSUtJWQlZTQ4OzU7JXAxJWQl
O20AG1s/NjloG1slaSVwMSVkOyVwMiVkcwAbbAAbbQACAAAASgCWAKwDAQEAAAcA
EwAYACoAMAA6AFoAYQBoAG8AdgB9AIQAiwCSAJkAoACnAK4AtQC8AMMAygDRANgA
3wDmAO0A9AD7AAIBCQEQARcBHgElASwBMwE6AUEBSAFPAVYBXQFkAWsBcgF5AYAB
hwGOAZUBnAGjAaoBsQG4Ab8BxgHKAc4B0gHWAdoB3gHiAeYB6gHuAfIB9gH8AQEC
AAADAAYACQAMAA8AEgAVABgAGwAgACUAKgAvADQAOAA9AEIARwBMAFEAVwBdAGMA
aQBvAHUAewCBAIcAjQCSAJcAnAChAKYArACyALgAvgDEAMoA0ADWANwA4gDoAO4A
9AD6AAABBgEMARIBGAEeASIBJwEsATEBNgE7AT8BQwFHAUsBTwFVAVsBYQFnAW0B
cwF5AX4BgwEbXTExMgcAG10xMjslcDElcwcAG1szSgAbXTUyOyVwMSVzOyVwMiVz
BwAbWzIgcQAbWyVwMSVkIHEAG1s/MTAwNjsxMDAwJT8lcDElezF9JT0ldGglZWwl
OwAbWzM7M34AG1szOzR+ABtbMzs1fgAbWzM7Nn4AG1szOzd+ABtbMTsyQgAbWzE7
M0IAG1sxOzRCABtbMTs1QgAbWzE7NkIAG1sxOzdCABtbMTszRgAbWzE7NEYAG1sx
OzVGABtbMTs2RgAbWzE7N0YAG1sxOzNIABtbMTs0SAAbWzE7NUgAG1sxOzZIABtb
MTs3SAAbWzI7M34AG1syOzR+ABtbMjs1fgAbWzI7Nn4AG1syOzd+ABtbMTszRAAb
WzE7NEQAG1sxOzVEABtbMTs2RAAbWzE7N0QAG1s2OzN+ABtbNjs0fgAbWzY7NX4A
G1s2OzZ+ABtbNjs3fgAbWzU7M34AG1s1OzR+ABtbNTs1fgAbWzU7Nn4AG1s1Ozd+
ABtbMTszQwAbWzE7NEMAG1sxOzVDABtbMTs2QwAbWzE7N0MAG1sxOzJBABtbMTsz
QQAbWzE7NEEAG1sxOzVBABtbMTs2QQAbWzE7N0EAG094ABtPdAAbT3YAG09yABtP
RQAbT2sAG09sABtPbwAbT24AG09qABtPbQAbT3AAG1syOW0AG1s5bQAbWzwlaSVw
MyVkOyVwMSVkOyVwMiVkOyU/JXA0JXRNJWVtJTsAQVgAWFQAQ3IAQ3MARTMATXMA
U2UAU3MAWE0Aa0RDMwBrREM0AGtEQzUAa0RDNgBrREM3AGtETgBrRE4zAGtETjQA
a0RONQBrRE42AGtETjcAa0VORDMAa0VORDQAa0VORDUAa0VORDYAa0VORDcAa0hP
TTMAa0hPTTQAa0hPTTUAa0hPTTYAa0hPTTcAa0lDMwBrSUM0AGtJQzUAa0lDNgBr
SUM3AGtMRlQzAGtMRlQ0AGtMRlQ1AGtMRlQ2AGtMRlQ3AGtOWFQzAGtOWFQ0AGtO
WFQ1AGtOWFQ2AGtOWFQ3AGtQUlYzAGtQUlY0AGtQUlY1AGtQUlY2AGtQUlY3AGtS
SVQzAGtSSVQ0AGtSSVQ1AGtSSVQ2AGtSSVQ3AGtVUABrVVAzAGtVUDQAa1VQNQBr
VVA2AGtVUDcAa2EyAGtiMQBrYjMAa2MyAGtwNQBrcEFERABrcENNQQBrcERJVgBr
cERPVABrcE1VTABrcFNVQgBrcFpSTwBybXh4AHNteHgAeG0A
__EOF_xterm-256color__
      ;;
    rxvt)
      cat <<'__EOF_rxvt__'
GgEuACYAEABuAQ0Ecnh2dHxyeHZ0IHRlcm1pbmFsIGVtdWxhdG9yIChYIFdpbmRv
dyBTeXN0ZW0pAAABAAABAQAAAAAAAAABAQAAAAAAAQAAAAAAAAABAAAAAAAAAAAB
UAAIABgA//////////////////////////8IAEAA/v///wAAAgAEABUAGgAiACYA
KgD//zUARgBIAEwAUwD//1UAXAD//2AA/////2QA/////2gAagBvAHQA/////30A
/////4IAhwCMAP//kQCTAJgA//+lAKoAsAC2AP/////IANYA////////+AD///wA
/////////gD//wMB//8HAf//DAESARgBHgEkASoBMAE2ATwBQgFIAU4BUwH//1gB
//9cAWEBZgFqAW4B//9yAXYBeQH/////////////////////////////////////
/////3wBhQGOAf//lwGgAakB//+yAf//////////////////uwHcAf////8OAhEC
HAIfAiECJAJnAv//agL//////////2wCcAJ0AngCfAL/////gAL//7MC////////
////////twL/////////////////////vgLDAv//xwL/////////////////////
////////////////////////////////////////zAL//9EC1gL//////////9sC
4ALlAv/////pAv//7gL////////zAv/////////////3Av0CAwMJAw8DFQMbAyED
JwMtAzMDOQM/A0UDSwNRA1cDXQNjA2kDbwN1A3sDgQOHA40DkwOZA58DpQOrA7ED
twO9A///////////////////////////////////////////////////wwP/////
////////////////////////////////////////////////////////yAPTA9gD
4APkA///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
/////////////////////////////+0D////////8QP7A////////wUECQQHAA0A
G1slaSVwMSVkOyVwMiVkcgAbWzNnABtbSBtbMkoAG1tLABtbSgAbWyVpJXAxJWRH
ABtbJWklcDElZDslcDIlZEgACgAbW0gAG1s/MjVsAAgAG1s/MjVoABtbQwAbW0EA
G1tNAA4AG1s1bQAbWzFtABs3G1s/NDdoABtbNGgAG1s3bQAbWzdtABtbNG0ADwAb
W20PABtbMkobWz80N2wbOAAbWzRsABtbMjdtABtbMjRtABtbPzVoJDwxMDAvPhtb
PzVsABtbPzQ3bBs9G1s/MWwAG1tyG1ttG1syShtbSBtbPzdoG1s/MTszOzQ7Nmwb
WzRsABtbTAB/ABtbM34AG1tCABtbOF4AG1syMX4AG1sxMX4AG1syMX4AG1sxMn4A
G1sxM34AG1sxNH4AG1sxNX4AG1sxN34AG1sxOH4AG1sxOX4AG1syMH4AG1s3fgAb
WzJ+ABtbRAAbWzZ+ABtbNX4AG1tDABtbYQAbW2IAG1tBABs+ABs9ABtbJXAxJWRN
ABtbJXAxJWRCABtbJXAxJWRAABtbJXAxJWRMABtbJXAxJWREABtbJXAxJWRDABtb
JXAxJWRBABs+G1sxOzM7NDs1OzZsG1s/N2gbW20bW3IbWzJKG1tIABtbchtbbRtb
MkobW0gbWz83aBtbPzE7Mzs0OzZsG1s0bBs+G1s/MTAwMGwbWz8yNWgAGzgAG1sl
aSVwMSVkZAAbNwAKABtNABtbMCU/JXA2JXQ7MSU7JT8lcDIldDs0JTslPyVwMSVw
MyV8JXQ7NyU7JT8lcDQldDs1JTttJT8lcDkldA4lZQ8lOwAbSAAJABtPdwAbT3kA
G091ABtPcQAbT3MAYGBhYWZmZ2dqamtrbGxtbW5ub29wcHFxcnJzc3R0dXV2dnd3
eHh5eXp6e3t8fH19fn4AG1taABsoQhspMAAbWzh+ABtPTQAbWzF+ABtbMyQAG1s0
fgAbWzgkABtbNyQAG1syJAAbW2QAG1s2JAAbWzUkABtbYwAbWzIzfgAbWzI0fgAb
WzI1fgAbWzI2fgAbWzI4fgAbWzI5fgAbWzMxfgAbWzMyfgAbWzMzfgAbWzM0fgAb
WzIzJAAbWzI0JAAbWzExXgAbWzEyXgAbWzEzXgAbWzE0XgAbWzE1XgAbWzE3XgAb
WzE4XgAbWzE5XgAbWzIwXgAbWzIxXgAbWzIzXgAbWzI0XgAbWzI1XgAbWzI2XgAb
WzI4XgAbWzI5XgAbWzMxXgAbWzMyXgAbWzMzXgAbWzM0XgAbWzIzQAAbWzI0QAAb
WzFLABtbJWklZDslZFIAG1s2bgAbWz8xOzJjABtbYwAbWzM5OzQ5bQAbW00AG1sz
JXAxJWRtABtbNCVwMSVkbQAbKEIAGygwAAACAAAAFgAuANwAAQEAAAUACgAOABIA
FwAcACEAJgArADAANAA5AD4AQwBIAEwAUABUAFgAXABgAAAAAwAGAAsAEAAUABkA
HwAlACsAMQA2ADsAQQBHAE0AUwBZAF8AYwBoAGwAcAB0ABtbM14AG1szQAAbW2IA
G09iABtbOF4AG1s4QAAbWzdeABtbN0AAG1syXgAbWzJAABtPZAAbWzZeABtbNkAA
G1s1XgAbWzVAABtPYwAbW2EAG09hABtPeAAbT3QAG092ABtPcgBBWABYVABrREM1
AGtEQzYAa0ROAGtETjUAa0VORDUAa0VORDYAa0hPTTUAa0hPTTYAa0lDNQBrSUM2
AGtMRlQ1AGtOWFQ1AGtOWFQ2AGtQUlY1AGtQUlY2AGtSSVQ1AGtVUABrVVA1AGth
MgBrYjEAa2IzAGtjMgA=
__EOF_rxvt__
      ;;
    screen)
      cat <<'__EOF_screen__'
GgEqACsAEABpAZkCc2NyZWVufFZUIDEwMC9BTlNJIFgzLjY0IHZpcnR1YWwgdGVy
bWluYWwAAAEAAAEAAAABAAAAAAEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAA
AQBQAAgAGAD//////////////////////////wgAQAD+/wAABAAGAAgAGQAeACUA
KQAtAP//OABJAEsATwBWAP//WABkAP//aABrAHEAdQD/////eQB7AIAAhQD//44A
kwD/////mACdAKIA//+nAKkArgD//7cAvADCAMgA////////ywD////////PAP//
0wD////////VAP//2gD//////////94A4gDoAOwA8AD0APoAAAEGAQwBEgEXAf//
HAH//yABJQEqAf///////y4BMgE6Af//////////////////////////////////
QgH//0UBTgFXAWABaQFyAXsBhAH//40B/////////////////////5YB/////6cB
qgG1AbgBugG9AREC//8UAv////////////////////////////8WAv//VwL/////
//////////9bAv////////////////////9iAv//////////////////////////
////////////////////////////////////////////////////////////////
/////////////////////////////////////////////2cCbQL/////////////
////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////9zAv//
////////////////////////////////////////////////////////////////
/////3gC////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////gQL///////+FAo8CG1taAAcADQAbWyVp
JXAxJWQ7JXAyJWRyABtbM2cAG1tIG1tKABtbSwAbW0oAG1slaSVwMSVkRwAbWyVp
JXAxJWQ7JXAyJWRIAAoAG1tIABtbPzI1bAAIABtbMzRoG1s/MjVoABtbQwAbTQAb
WzM0bAAbW1AAG1tNAA4AG1s1bQAbWzFtABtbPzEwNDloABtbMm0AG1s0aAAbWzdt
ABtbM20AG1s0bQAPABtbbQ8AG1s/MTA0OWwAG1s0bAAbWzIzbQAbWzI0bQAbZwAb
KTAAG1tMAH8AG1szfgAbT0IAG09QABtbMjF+ABtPUQAbT1IAG09TABtbMTV+ABtb
MTd+ABtbMTh+ABtbMTl+ABtbMjB+ABtbMX4AG1syfgAbT0QAG1s2fgAbWzV+ABtP
QwAbT0EAG1s/MWwbPgAbWz8xaBs9ABtFABtbJXAxJWRQABtbJXAxJWRNABtbJXAx
JWRCABtbJXAxJWRAABtbJXAxJWRTABtbJXAxJWRMABtbJXAxJWREABtbJXAxJWRD
ABtbJXAxJWRBABtjG1s/MTAwMGwbWz8yNWgAGzgAG1slaSVwMSVkZAAbNwAKABtN
ABtbMCU/JXA2JXQ7MSU7JT8lcDEldDszJTslPyVwMiV0OzQlOyU/JXAzJXQ7NyU7
JT8lcDQldDs1JTslPyVwNSV0OzIlO20lPyVwOSV0DiVlDyU7ABtIAAkAKyssLC0t
Li4wMGBgYWFmZmdnaGhpaWpqa2tsbG1tbm5vb3BwcXFycnNzdHR1dXZ2d3d4eHl5
enp7e3x8fX1+fgAbW1oAGyhCGykwABtbNH4AG1syM34AG1syNH4AG1sxSwAbWzM5
OzQ5bQAbW00AG1szJXAxJWRtABtbNCVwMSVkbQAAAgABAAIABwAbAAEBAQAAAAQA
AAADAAYACQAMABsoQgAbKCVwMSVjAEFYAEcwAFU4AEUwAFMwAA==
__EOF_screen__
      ;;
    screen-256color)
      cat <<'__EOF_screen-256color__'
GgErACsADwBpAQ0Dc2NyZWVuLTI1NmNvbG9yfEdOVSBTY3JlZW4gd2l0aCAyNTYg
Y29sb3JzAAABAAABAAAAAQAAAAABAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA
AAFQAAgAGAD//////////////////////////wAB/38AAAQABgAIABkAHgAlACkA
LQD//zgASQBLAE8AVgD//1gAZAD//2gAawBxAHUA/////3kAewCAAIUA//+OAJMA
/////5gAnQCiAP//pwCpAK4A//+3ALwAwgDIAP///////8sA////////zwD//9MA
////////1QD//9oA///////////eAOIA6ADsAPAA9AD6AAABBgEMARIBFwH//xwB
//8gASUBKgH///////8uATIBOgH//////////////////////////////////0IB
//9FAU4BVwFgAWkBcgF7AYQBjQGWAf////////////////////+fAf////+wAbMB
vgHBAcMBxgEaAv//HQL/////////////////////////////HwL//2AC////////
////////ZAL/////////////////////awL/////////////////////////////
////////////////////////////////////////////////////////////////
//////////////////////////////////////////9wAnYC////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////fAL/////
////////////////////////////////////////////////////////////////
//+BAv//////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
/////////////////////////////4oC////////jgLNAhtbWgAHAA0AG1slaSVw
MSVkOyVwMiVkcgAbWzNnABtbSBtbSgAbW0sAG1tKABtbJWklcDElZEcAG1slaSVw
MSVkOyVwMiVkSAAKABtbSAAbWz8yNWwACAAbWzM0aBtbPzI1aAAbW0MAG00AG1sz
NGwAG1tQABtbTQAOABtbNW0AG1sxbQAbWz8xMDQ5aAAbWzJtABtbNGgAG1s3bQAb
WzNtABtbNG0ADwAbW20PABtbPzEwNDlsABtbNGwAG1syM20AG1syNG0AG2cAGykw
ABtbTAB/ABtbM34AG09CABtPUAAbWzIxfgAbT1EAG09SABtPUwAbWzE1fgAbWzE3
fgAbWzE4fgAbWzE5fgAbWzIwfgAbWzF+ABtbMn4AG09EABtbNn4AG1s1fgAbT0MA
G09BABtbPzFsGz4AG1s/MWgbPQAbRQAbWyVwMSVkUAAbWyVwMSVkTQAbWyVwMSVk
QgAbWyVwMSVkQAAbWyVwMSVkUwAbWyVwMSVkTAAbWyVwMSVkRAAbWyVwMSVkQwAb
WyVwMSVkVAAbWyVwMSVkQQAbYxtbPzEwMDBsG1s/MjVoABs4ABtbJWklcDElZGQA
GzcACgAbTQAbWzAlPyVwNiV0OzElOyU/JXAxJXQ7MyU7JT8lcDIldDs0JTslPyVw
MyV0OzclOyU/JXA0JXQ7NSU7JT8lcDUldDsyJTttJT8lcDkldA4lZQ8lOwAbSAAJ
ACsrLCwtLS4uMDBgYGFhZmZnZ2hoaWlqamtrbGxtbW5ub29wcHFxcnJzc3R0dXV2
dnd3eHh5eXp6e3t8fH19fn4AG1taABsoQhspMAAbWzR+ABtbMjN+ABtbMjR+ABtb
MUsAG1szOTs0OW0AG1tNABtbJT8lcDElezh9JTwldDMlcDElZCVlJXAxJXsxNn0l
PCV0OSVwMSV7OH0lLSVkJWUzODs1OyVwMSVkJTttABtbJT8lcDElezh9JTwldDQl
cDElZCVlJXAxJXsxNn0lPCV0MTAlcDElezh9JS0lZCVlNDg7NTslcDElZCU7bQAA
AgABAAIABwAbAAEBAQAAAAQAAAADAAYACQAMABsoQgAbKCVwMSVjAEFYAEcwAFU4
AEUwAFMwAA==
__EOF_screen-256color__
      ;;
    vt100)
      cat <<'__EOF_vt100__'
GgEsACYABwAOAR4CdnQxMDB8dnQxMDAtYW18ZGVjIHZ0MTAwICh3L2FkdmFuY2Vk
IHZpZGVvKQAAAQAAAQAAAAAAAAAAAAEAAAAAAAEAAQAAAAAAAAAAAAAAAAAAAVAA
CAAYAP///////wMA//8AAAIABAAVABoAJgAuAP////83AEwATgD//1IA/////1QA
//9cAP////////////9kAGYAbwD///////////////94AIEAigD//5MAlQD/////
//+eAKYA//////////////////////////+uAP////////////+wAP///////7QA
uAC8AMAAxADIAMwA0ADUANgA3AD////////gAP///////+QA////////6ADsAPQA
///8AP//AAEEAQgB/////////////////////////////wwB////////FQEeAf//
JwH///////8wATUBOgH/////PwH/////VwH//1oBXQFfAWYBsgH//7UB////////
//+3AbsBvwHDAccB/////8sB///////////+AQQC/////woC////////////////
////////EQL/////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
/////////////////////////////xUCBwANABtbJWklcDElZDslcDIlZHIAG1sz
ZwAbW0gbW0okPDUwPgAbW0skPDM+ABtbSiQ8NTA+ABtbJWklcDElZDslcDIlZEgk
PDU+AAoAG1tIAAgAG1tDJDwyPgAbW0EkPDI+AA4AG1s1bSQ8Mj4AG1sxbSQ8Mj4A
G1s3bSQ8Mj4AG1s3bSQ8Mj4AG1s0bSQ8Mj4ADwAbW20PJDwyPgAbW20kPDI+ABtb
bSQ8Mj4ACAAbT0IAG095ABtPUAAbT3gAG09RABtPUgAbT1MAG090ABtPdQAbT3YA
G09sABtPdwAbT0QAG09DABtPQQAbWz8xbBs+ABtbPzFoGz0AcGYxAHBmMgBwZjMA
cGY0ABtbJXAxJWRCABtbJXAxJWREABtbJXAxJWRDABtbJXAxJWRBABtbMGkAG1s0
aQAbWzVpABs8Gz4bWz8zOzQ7NWwbWz83OzhoG1tyABs4ABs3AAoAG00kPDU+ABtb
MCU/JXAxJXA2JXwldDsxJTslPyVwMiV0OzQlOyU/JXAxJXAzJXwldDs3JTslPyVw
NCV0OzUlO20lPyVwOSV0DiVlDyU7JDwyPgAbSAAJABtPcQAbT3MAG09yABtPcAAb
T24AYGBhYWZmZ2dqamtrbGxtbW5ub29wcHFxcnJzc3R0dXV2dnd3eHh5eXp6e3t8
fH19fn4AG1s/N2gAG1s/N2wAGyhCGykwABtPTQAbWzFLJDwzPgA=
__EOF_vt100__
      ;;
    vt102)
      cat <<'__EOF_vt102__'
GgEQACYABwAOATQCdnQxMDJ8ZGVjIHZ0MTAyAAABAAABAAAAAAAAAAAAAQAAAAAA
AQABAAAAAAAAAAAAAAAAAAABUAAIABgA////////AwD//wAAAgAEABUAGgAmAC4A
/////zcATABOAP//UgD/////VAD//1wA//9kAGgA/////2wAbgB3AP///////4AA
/////4UAjgCXAP//oACiAP////+rALAAuAD/////////////////////wAD//8QA
/////////////8YA////////ygDOANIA1gDaAN4A4gDmAOoA7gDyAP////////YA
////////+gD////////+AAIBCgH//xIB//8WARoBHgH/////////////////////
////////IgH///////8rATQB//89Af///////0YBSwFQAf////9VAf////9tAf//
cAFzAXUBfAHIAf//ywH//////////80B0QHVAdkB3QH/////4QH//////////xQC
GgL/////IAL///////////////////////8nAv//////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////KwIHAA0A
G1slaSVwMSVkOyVwMiVkcgAbWzNnABtbSBtbSiQ8NTA+ABtbSyQ8Mz4AG1tKJDw1
MD4AG1slaSVwMSVkOyVwMiVkSCQ8NT4ACgAbW0gACAAbW0MkPDI+ABtbQSQ8Mj4A
G1tQABtbTQAOABtbNW0kPDI+ABtbMW0kPDI+ABtbNGgAG1s3bSQ8Mj4AG1s3bSQ8
Mj4AG1s0bSQ8Mj4ADwAbW20PJDwyPgAbWzRsABtbbSQ8Mj4AG1ttJDwyPgAbW0wA
CAAbT0IAG095ABtPUAAbT3gAG09RABtPUgAbT1MAG090ABtPdQAbT3YAG09sABtP
dwAbT0QAG09DABtPQQAbWz8xbBs+ABtbPzFoGz0AcGYxAHBmMgBwZjMAcGY0ABtb
JXAxJWRCABtbJXAxJWREABtbJXAxJWRDABtbJXAxJWRBABtbMGkAG1s0aQAbWzVp
ABs8Gz4bWz8zOzQ7NWwbWz83OzhoG1tyABs4ABs3AAoAG00kPDU+ABtbMCU/JXAx
JXA2JXwldDsxJTslPyVwMiV0OzQlOyU/JXAxJXAzJXwldDs3JTslPyVwNCV0OzUl
O20lPyVwOSV0DiVlDyU7JDwyPgAbSAAJABtPcQAbT3MAG09yABtPcAAbT24AYGBh
YWZmZ2dqamtrbGxtbW5ub29wcHFxcnJzc3R0dXV2dnd3eHh5eXp6e3t8fH19fn4A
G1s/N2gAG1s/N2wAGyhCGykwABtPTQAbWzFLJDwzPgA=
__EOF_vt102__
      ;;
  esac
}

# What QNAP's screenfix did for screen, built in: the utmp file and the eight terminfo files, each only when missing.
# Left out on purpose:
#   - its "screen -Rd helpdesk" line for ~/.profile: /root is a ramdisk on QTS, nothing goes into a home folder, and it would start screen at every login
#   - removing the /share/homes link: that changes the NAS beyond this session
#   - its own screen session "helpdesk": the script starts its own
screen_files() { # sets SF_WROTE and SF_FAIL
  local __n __d __f __dec __um
  SF_WROTE=""
  SF_FAIL=""
  __um=$(umask)
  umask 022 # screen and every later login read these files
  if [ ! -e "$F_UTMP" ]; then
    if mkdir -p "${F_UTMP%/*}" 2>/dev/null && touch "$F_UTMP" 2>/dev/null; then SF_WROTE=" $F_UTMP"; else SF_FAIL=" $F_UTMP"; fi
  fi
  for __n in xterm xterm-color xterm-256color rxvt screen screen-256color vt100 vt102; do
    __d="$TERMINFO_DIR/${__n%"${__n#?}"}"
    __f="$__d/$__n"
    if [ -f "$__f" ]; then continue; fi
    mkdir -p "$__d" 2>/dev/null
    for __dec in "openssl enc -base64 -d" "base64 -d" "busybox base64 -d"; do
      rm -f "$__f.new"
      if have "${__dec%% *}" && terminfo_data "$__n" | $__dec >"$__f.new" 2>/dev/null && [ -s "$__f.new" ]; then break; fi
    done
    if [ -s "$__f.new" ] && mv -f "$__f.new" "$__f" 2>/dev/null; then
      SF_WROTE="$SF_WROTE ${__f#"$TERMINFO_DIR/"}"
    else
      rm -f "$__f.new"
      SF_FAIL="$SF_FAIL ${__f#"$TERMINFO_DIR/"}"
    fi
  done
  umask "$__um"
}

screen_term() { # the TERM for the screen child: the operator's own when it has a terminfo entry, else xterm
  if [ -n "$TERM" ] && [ -f "$TERMINFO_DIR/${TERM%"${TERM#?}"}/$TERM" ]; then echo "$TERM"; else echo xterm; fi
}

fix_screen() { # 0 = screen is available, 1 = go on without screen
  local __a
  echo "The 'screen' command is missing or does not work."
  say "Fixing what screen needs: $F_UTMP and the terminfo files in $TERMINFO_DIR"
  screen_files
  if [ -n "$SF_WROTE" ]; then
    ok "Written:$SF_WROTE"
  elif [ -z "$SF_FAIL" ]; then
    say "Nothing was missing: $F_UTMP and the eight terminfo files are there."
  fi
  if [ -n "$SF_FAIL" ]; then warn "Could not write:$SF_FAIL"; fi
  if have screen; then return 0; fi
  printf 'Continue WITHOUT screen? A dropped SSH session stops the work between steps. [y/N]: '
  read -r __a
  case "$__a" in
    y | Y | t | T) return 1 ;;
    *) exit 1 ;;
  esac
}

start_screen() {
  local __mark="$TMPD/$SESSION.started" __t
  if ! have screen; then fix_screen || return 0; fi
  if screen -ls 2>/dev/null | grep -q "[.]$SESSION"; then
    echo "The screen session '$SESSION' already exists - attaching."
    sleep 1
    exec screen -U -d -r "$SESSION"
  fi
  rm -f "$__mark"
  echo "Starting in the screen session '$SESSION'.  Detach: Ctrl+a d   Reattach: screen -U -r $SESSION"
  echo "Scroll back inside screen: Ctrl+a Esc, then PgUp/PgDn; Esc leaves."
  sleep 2
  screen -U -h 20000 -S "$SESSION" sh "$RUNCOPY" --cwd "$CWD" --in-screen ${DEBUG:+--debug} ${AUTO_START:+--auto} ${ALLOW_NO_BACKUP:+--allow-no-backup}
  if [ -f "$__mark" ]; then
    if screen -ls 2>/dev/null | grep -q "[.]$SESSION"; then
      echo "The script keeps running in the background. Reattach: screen -U -r $SESSION"
    fi
    exit 0
  fi
  echo "screen did not start the script."
  if fix_screen; then
    __t=$(screen_term)
    if [ "$__t" != "$TERM" ]; then say "No terminfo entry for TERM='$TERM' on this NAS: screen starts with TERM=$__t."; fi
    TERMINFO="$TERMINFO_DIR" TERM="$__t" screen -U -h 20000 -S "$SESSION" sh "$RUNCOPY" --cwd "$CWD" --in-screen ${DEBUG:+--debug} ${AUTO_START:+--auto} ${ALLOW_NO_BACKUP:+--allow-no-backup}
    if [ -f "$__mark" ]; then exit 0; fi
    printf 'screen still does not work. Continue WITHOUT screen? [y/N]: '
    read -r ANS
    case "$ANS" in y | Y | t | T) ;; *) exit 1 ;; esac
  fi
  return 0
}

bootstrap() {
  local __self
  if [ -n "$QPR_TEST" ]; then
    CWD=${CWD:-$(pwd)}
    return 0
  fi
  if [ "$(id -u 2>/dev/null)" != 0 ]; then
    echo "Run as admin over SSH (uid 0); QTS has no sudo."
    exit 1
  fi
  case "$0" in */*) __self=$0 ;; *) __self="./$0" ;; esac
  if [ ! -f "$__self" ]; then
    echo "Save the script to a file and run: sh qnap-pool-repair.sh"
    exit 1
  fi
  RUNCOPY="$TMPD/$SESSION.run.sh"
  if [ -z "$CWD" ]; then
    # work from a copy in /tmp: the script must not sit on a volume that is about to be unmounted. md9 stays
    # mounted too, but a copy there survives a reboot and could be run by mistake later
    CWD=$(cd "$(dirname "$__self")" 2>/dev/null && pwd)
    if ! cp "$__self" "$RUNCOPY.$$" || ! mv -f "$RUNCOPY.$$" "$RUNCOPY"; then
      echo "Cannot copy the script to $TMPD."
      exit 1
    fi
    cd / || exit 1
    exec sh "$RUNCOPY" --cwd "${CWD:-/root}" ${NO_SCREEN:+--no-screen} ${DEBUG:+--debug} ${AUTO_START:+--auto} ${ALLOW_NO_BACKUP:+--allow-no-backup} ${SELFTEST:+--selftest}
  fi
  cd / || exit 1
  if [ -n "$IN_SCREEN" ]; then
    : >"$TMPD/$SESSION.started"
    return 0
  fi
  if [ -n "$STY" ] || [ -n "$NO_SCREEN" ]; then return 0; fi
  start_screen
}

# ==================================================================================================
while [ $# -gt 0 ]; do
  case "$1" in
    --no-screen) NO_SCREEN=1 ;;
    --selftest)
      SELFTEST=1
      NO_SCREEN=1
      ;;
    --in-screen) IN_SCREEN=1 ;;
    --debug | -d) DEBUG=1 ;;
    --auto) AUTO_START=1 ;;
    --allow-no-backup) ALLOW_NO_BACKUP=1 ;;
    --cwd)
      shift
      CWD=$1
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    -V | --version)
      echo "qnap-pool-repair $VERSION"
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      usage
      exit 2
      ;;
  esac
  shift
done

# traced wrappers for the step functions (see "Call trace and debug mode")
_wrap do_diag do_prepare do_backup do_repair do_startup finish \
  choose_workdir need_workdir pick_pdata thin_check_run read_super clear_flag_if_set \
  meta_up tmp_up require_offline lvm_gate raid_gate compute_stack \
  umount_one dm_remove stop_services stop_qsnapman cfg_edit unswap \
  path_tmp test_mount path_swap_test backup_gate path_commit path_legacy \
  path_flag choose_path tool_tpcollect tool_clear_flag tool_restore_backup tool_snapscan \
  tool_restoremissing tool_fullrescan tool_orphans tool_sbrestore make_copy path_rebuild auto_run fs_check tool_settings tools_menu logs_menu detect_pool \
  detect_tmplv

bootstrap
lock_take
if [ -n "$SELFTEST" ]; then # --selftest: the command check and the self-test, nothing else
  LOGDIR="$TMPD/$SESSION-selftest"
  mkdir -p "$LOGDIR"
  LOG="$LOGDIR/session.log"
  need_check && selftest
  __st=$?
  say "Log: $LOG"
  exit "$__st"
fi
trap '' INT QUIT HUP TSTP # Ctrl+C and a dropped session do not interrupt an operation
trap 'TERM_REQ=1' TERM
trap 'if [ -n "$LOCKDIR" ]; then rm -rf "$LOCKDIR"; fi' EXIT
init_session
if [ -n "$AUTO_START" ]; then auto_run; fi
main_menu
