#!/bin/bash
# NOQ Purser: restore from the box's disk, and the restore drill. Any Linux machine, as root.
# Not the protected server: use a clean machine (a laptop, or a VM with the network off).
#
#   purser restore --disk /dev/sdX [--list]                          generations on the disk
#   purser restore --disk /dev/sdX --copy <id> --source <name> --to <dir>   copy one source out
#   purser restore --disk /dev/sdX --test <id> [drill options]      the restore drill
#
#   --disk <device>   the box's disk on USB; opened read-only with the recovery passphrase
#   --mounted <dir>   instead of --disk: a Purser disk you opened and mounted yourself
#
# The drill (--test) checks the generation against its list, then brings every source back with
# its own tool, in scratch space, without network:
#   pgBackRest  restore (--type=immediate; a weekly/monthly copy --type=none), optionally PostgreSQL
#               started on it (socket only) with SELECT 1 and your query
#   borg        the newest archive read in full (extract --dry-run), or one path extracted
#   restic      check, then the newest snapshot restored
#   plain dir   the list check
# When every source came back, the generation gets the mark "verified good (drill <date>)" on the
# disk (denetim/iyi/<id>). The box reads it in its next window, shows it and keeps the newest two
# drilled generations whatever the calendar does. A generation with an uncleared suspicion is
# drilled but never marked.
#
# Drill options:
#   --pg-start                  start PostgreSQL on the restored data and run SELECT 1
#   --pg-query <sql>            also run this query and show its output (implies --pg-start)
#   --pg-bin <dir>              PostgreSQL programs (default /usr/lib/postgresql/<version>/bin)
#   --pg-user <user>            runs PostgreSQL (default postgres)
#   --pg-stanza <name>          when the repository holds more than one stanza
#   --pg-cipher-pass-file <f>   pgBackRest repo1-cipher-pass (otherwise asked; empty: not encrypted)
#   --borg-pass-file <f>        borg passphrase (otherwise asked; empty: none)
#   --borg-extract <path>       extract this path of the newest archive for real
#   --restic-pass-file <f>      restic password (otherwise asked)
#   --work <dir>                scratch space (default a new directory under /var/tmp); removed at the end
#   --keep                      keep the scratch space (it holds restored data: delete it yourself)
#   --no-list-check             skip the list check (the box checked every file when it wrote it)
#   --no-mark                   do not write the mark (the disk is then never opened read-write)
set -uo pipefail
export LC_ALL=C
HERE=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
VERSION=$(cat "$HERE/../share/noq-purser/version" 2>/dev/null || cat "$HERE/version" 2>/dev/null || echo dev)
ID_RE='^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}Z$'
NAME_RE='^[A-Za-z0-9._+-]{1,64}$'
MAP=purser-restore

DISK="" MOUNTED="" ACTION=list GID="" SOURCE="" TO="" WORK="" KEEP=0 LISTCHECK=1 MARK=1
PG_START=0 PG_QUERY="" PG_BIN="" PG_USER=postgres PG_STANZA="" PG_PASS_FILE="" BORG_PASS_FILE="" BORG_PATH="" RESTIC_PASS_FILE=""
usage() { sed -n '2,41p' "$0" | sed 's/^# \{0,1\}//'; }
while [ $# -gt 0 ]; do
  case $1 in
    --disk) DISK=${2:-}; shift 2 ;;
    --mounted) MOUNTED=${2:-}; shift 2 ;;
    --list) ACTION=list; shift ;;
    --test) ACTION="test"; GID=${2:-}; shift 2 ;;
    --copy) ACTION=copy; GID=${2:-}; shift 2 ;;
    --source) SOURCE=${2:-}; shift 2 ;;
    --to) TO=${2:-}; shift 2 ;;
    --work) WORK=${2:-}; shift 2 ;;
    --keep) KEEP=1; shift ;;
    --no-list-check) LISTCHECK=0; shift ;;
    --no-mark) MARK=0; shift ;;
    --pg-start) PG_START=1; shift ;;
    --pg-query) PG_START=1; PG_QUERY=${2:-}; shift 2 ;;
    --pg-bin) PG_BIN=${2:-}; shift 2 ;;
    --pg-user) PG_USER=${2:-}; shift 2 ;;
    --pg-stanza) PG_STANZA=${2:-}; shift 2 ;;
    --pg-cipher-pass-file) PG_PASS_FILE=${2:-}; shift 2 ;;
    --borg-pass-file) BORG_PASS_FILE=${2:-}; shift 2 ;;
    --borg-extract) BORG_PATH=${2:-}; shift 2 ;;
    --restic-pass-file) RESTIC_PASS_FILE=${2:-}; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "purser restore: unknown option $1 (see --help)" >&2; exit 2 ;;
  esac
done
die() { echo "purser restore: $*" >&2; exit 1; }
say() { printf '%s\n' "$*"; }
[ "$(uname -s)" = Linux ] || die "Linux only (the disk is LUKS2 + btrfs)"
[ "$(id -u)" = 0 ] || die "run as root"
{ [ -n "$DISK" ] && [ -z "$MOUNTED" ]; } || { [ -z "$DISK" ] && [ -n "$MOUNTED" ]; } || die "give --disk <device> or --mounted <dir>"
case $ACTION in test|copy) [[ $GID =~ $ID_RE ]] || die "generation id expected, e.g. 2026-11-27T01-37Z" ;; esac

ROOT="" OPENED=0 MOUNTPOINT="" PASS="" PGPID_DIR=""
# shellcheck disable=SC2317  # run from the EXIT trap
cleanup() {
  [ -n "$PGPID_DIR" ] && pg_stop
  if [ "$OPENED" = 1 ]; then
    mountpoint -q "$MOUNTPOINT" && umount "$MOUNTPOINT"
    cryptsetup close "$MAP" 2>/dev/null || true
    rmdir "$MOUNTPOINT" 2>/dev/null || true
  fi
  if [ -n "$WORK" ] && [ -d "$WORK" ] && [ "$KEEP" = 0 ] && [ -e "$WORK/.purser-restore" ]; then rm -rf --one-file-system -- "$WORK"; fi
  PASS=""
}
trap cleanup EXIT
trap 'exit 130' INT TERM

# --- the disk ---
open_disk() {   # open_disk ro|rw
  local mode=$1
  if [ -z "$PASS" ]; then
    lsblk -dno SIZE,MODEL "$DISK" 2>/dev/null | sed 's/^/disk: /'
    cryptsetup isLuks "$DISK" 2>/dev/null || die "$DISK is not a LUKS disk (give the whole disk, e.g. /dev/sdX)"
    printf 'recovery passphrase (from the paper pack): ' >&2
    IFS= read -rs PASS || PASS=""; echo >&2
    [ -n "$PASS" ] || die "no passphrase"
  fi
  local ro=(--readonly); [ "$mode" = rw ] && ro=()
  printf '%s' "$PASS" | cryptsetup open "${ro[@]}" --key-file=- "$DISK" "$MAP" || die "the disk did not open (wrong passphrase? a damaged header: docs/restore.md)"
  OPENED=1
  MOUNTPOINT=$(mktemp -d /run/purser-restore.XXXXXX)
  local o=ro; [ "$mode" = rw ] && o=rw
  mount -o "$o,noatime" "/dev/mapper/$MAP" "$MOUNTPOINT" || die "could not mount the disk"
  ROOT=$MOUNTPOINT
}
close_disk() {
  sync
  mountpoint -q "$MOUNTPOINT" && umount "$MOUNTPOINT"
  cryptsetup close "$MAP"; OPENED=0; rmdir "$MOUNTPOINT" 2>/dev/null || true
}
if [ -n "$DISK" ]; then open_disk ro
else
  [ -d "$MOUNTED" ] || die "$MOUNTED is not a directory"; ROOT=$(readlink -f "$MOUNTED")
fi
[ -d "$ROOT/nesil" ] && [ -d "$ROOT/denetim" ] || die "not a NOQ Purser disk (no nesil/ and denetim/)"
G=$ROOT/nesil A=$ROOT/denetim

kv() { sed -n "s/^$2=//p" "$1" 2>/dev/null | tail -1; }
suspect_open() { [ -e "$A/supheli/$1" ] && [ ! -e "$A/temiz/$1" ]; }
tree_of() { if [ -d "$G/gen-$1" ]; then echo "$G/gen-$1"; elif [ -d "$G/uzun-$1" ]; then echo "$G/uzun-$1"; else return 1; fi; }

# --- list ---
list_generations() {
  local d id kind v marks
  printf '%-19s %-14s %-9s %s\n' generation kept verdict marks
  for d in "$G"/gen-* "$G"/uzun-*; do
    [ -d "$d" ] || continue
    id=${d##*/}; kind=daily; [[ $id == uzun-* ]] && kind=weekly/monthly; id=${id#*-}
    [[ $id =~ $ID_RE ]] || continue
    v=ok; [ -n "$(kv "$A/meta/$id" uyari)" ] && v=warning; [ -n "$(kv "$A/meta/$id" suphe)" ] && v=suspect
    marks=""
    [ -e "$A/supheli/$id" ] && { if [ -e "$A/temiz/$id" ]; then marks+=" suspicion-cleared"; else marks+=" SUSPECT"; fi; }
    [ -e "$A/pin/$id" ] && marks+=" pinned"
    if [ -f "$A/iyi/$id" ]; then
      case $(kv "$A/iyi/$id" yol) in
        tatbikat) marks+=" verified-good(drill $(date -d "@$(kv "$A/iyi/$id" at)" +%F 2>/dev/null || echo ?))" ;;
        elle) marks+=" good-by-hand(no drill)" ;;
      esac
    fi
    printf '%-19s %-14s %-9s%s\n' "$id" "$kind" "$v" "$marks"
  done | sort -u
  say ""
  say "Return point: the newest verified-good generation from before the incident began; if there is none,"
  say "drill the newest generation from before the incident without an uncleared suspicion, then return to it."
}

# --- the list check ---
list_check() {   # list_check <tree> <id>
  local t=$1 id=$2 l=$A/liste/$2.list opt=()
  [ -f "$l" ] || { say "  list: missing ($l)"; return 1; }
  [[ $t == */uzun-* ]] && opt=(--ignore-missing)
  say "  list: checking every file against the box's list (this reads the whole generation) ..."
  if (cd "$t" && grep -v '^#' "$l" | sha256sum --quiet --strict -c "${opt[@]}" -) ; then say "  list: matches"; return 0; fi
  say "  list: DOES NOT MATCH"; return 1
}

kind_of() {   # kind_of <dir>
  local d=$1
  if compgen -G "$d/backup/*/backup.info*" >/dev/null; then echo pgbackrest
  elif [ -f "$d/config" ] && grep -q '^\[repository\]' "$d/config" 2>/dev/null && [ -d "$d/data" ]; then echo borg
  elif [ -f "$d/config" ] && [ -d "$d/keys" ] && [ -d "$d/snapshots" ]; then echo restic
  else echo dir; fi
}

# Tools run without network where the kernel allows it.
nonet() { if unshare -n true 2>/dev/null; then unshare -n -- "$@"; else "$@"; fi; }

ask_secret() {   # ask_secret <prompt> <file or ""> -> the secret on stdout
  if [ -n "$2" ]; then [ -r "$2" ] || die "cannot read $2"; head -c 4096 "$2" | tr -d '\n'; return; fi
  local s; printf '%s: ' "$1" >&2; IFS= read -rs s || s=""; echo >&2; printf '%s' "$s"
}

# --- pgBackRest ---
pg_stop() {
  [ -n "$PGPID_DIR" ] || return 0
  local d=$PGPID_DIR; PGPID_DIR=""
  [ -f "$d/postmaster.pid" ] || return 0
  runuser -u "$PG_USER" -- "$PGBIN/pg_ctl" -D "$d" -m fast -w stop >/dev/null 2>&1 || true
}
drill_pgbackrest() {   # drill_pgbackrest <repo> <name> <long 0|1> -> result token on stdout (fd 3 for text)
  local repo=$1 name=$2 long=$3 st n w=$WORK/$2 conf pass type v out
  command -v pgbackrest >/dev/null || { say "  $name: pgbackrest is not installed on this machine" >&3; return 1; }
  if [ -n "$PG_STANZA" ]; then st=$PG_STANZA
  else
    n=$(find "$repo/backup" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | grep -cE "$NAME_RE")
    [ "$n" = 1 ] || { say "  $name: $n stanzas in the repository; give --pg-stanza" >&3; return 1; }
    st=$(find "$repo/backup" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | grep -E "$NAME_RE")
  fi
  [[ $st =~ $NAME_RE ]] || { say "  $name: stanza name not allowed" >&3; return 1; }
  install -d -m 0700 "$w" "$w/log" "$w/lock" "$w/spool" "$w/data"
  pass=$(ask_secret "$name: pgBackRest repo1-cipher-pass (empty: not encrypted)" "$PG_PASS_FILE")
  conf=$w/pgbackrest.conf
  ( umask 077
    printf '[global]\nrepo1-path=%s\nlog-path=%s\nlock-path=%s\nspool-path=%s\nlog-level-console=warn\nlog-level-file=off\n' \
      "$repo" "$w/log" "$w/lock" "$w/spool"
    [ -n "$pass" ] && printf 'repo1-cipher-type=aes-256-cbc\nrepo1-cipher-pass=%s\n' "$pass"
    printf '[%s]\npg1-path=%s\n' "$st" "$w/data" ) > "$conf"
  pass=""
  type=immediate; [ "$long" = 1 ] && type=none
  say "  $name: pgBackRest restore of stanza $st (--type=$type) ..." >&3
  # The restored cluster must neither archive into nor read from anything but this disk. Recovery
  # uses the WAL inside the backup (archive-copy=y) and, when PostgreSQL can read it, the archive.
  local rec=()
  [ "$type" = none ] || rec=(--recovery-option="restore_command=pgbackrest --config=$conf --stanza=$st archive-get %f \"%p\"")
  if ! out=$(nonet pgbackrest --config="$conf" --stanza="$st" --type="$type" --archive-mode=off "${rec[@]}" restore 2>&1); then
    say "  $name: restore FAILED: $(tail -3 <<< "$out" | tr '\n' ' ')" >&3; return 1
  fi
  say "  $name: restored ($(du -sh "$w/data" | cut -f1))" >&3
  if [ "$PG_START" = 0 ]; then echo geri_yuklendi; return 0; fi
  v=$(tr -cd '0-9' < "$w/data/PG_VERSION" 2>/dev/null)
  PGBIN=${PG_BIN:-/usr/lib/postgresql/$v/bin}
  [ -x "$PGBIN/pg_ctl" ] || { say "  $name: PostgreSQL $v programs not found ($PGBIN); give --pg-bin" >&3; return 1; }
  id "$PG_USER" >/dev/null 2>&1 || { say "  $name: user $PG_USER does not exist; give --pg-user" >&3; return 1; }
  # Debian keeps postgresql.conf outside the data directory: start with a configuration of our own.
  install -d -m 0700 "$w/pg" "$w/sock"
  printf "listen_addresses = ''\nunix_socket_directories = '%s'\nport = 5439\ndata_directory = '%s'\nhba_file = '%s/pg_hba.conf'\nident_file = '%s/pg_ident.conf'\narchive_mode = off\n" \
    "$w/sock" "$w/data" "$w/pg" "$w/pg" > "$w/pg/postgresql.conf"
  # recovery refuses to run with fewer slots than the server had: take them from the control file
  "$PGBIN/pg_controldata" "$w/data" 2>/dev/null | awk -F': *' '
    $1 == "max_connections setting" { print "max_connections = " $2 }
    $1 == "max_worker_processes setting" { print "max_worker_processes = " $2 }
    $1 == "max_wal_senders setting" { print "max_wal_senders = " $2 }
    $1 == "max_prepared_xacts setting" { print "max_prepared_transactions = " $2 }
    $1 == "max_locks_per_xact setting" { print "max_locks_per_transaction = " $2 }' | grep -E '^[a-z_]+ = [0-9]+$' >> "$w/pg/postgresql.conf"
  printf 'local all all trust\n' > "$w/pg/pg_hba.conf"; : > "$w/pg/pg_ident.conf"
  # what the backup's own postgresql.auto.conf preloads may not be installed here
  sed -i '/^[[:space:]]*shared_preload_libraries[[:space:]]*=/d' "$w/data/postgresql.auto.conf" 2>/dev/null || true
  # PostgreSQL reads the archive itself only if it can; otherwise recovery uses the backup's own WAL
  if ! runuser -u "$PG_USER" -- test -r "$repo/archive" 2>/dev/null; then
    sed -i '/^[[:space:]]*restore_command[[:space:]]*=/d' "$w/data/postgresql.auto.conf" 2>/dev/null || true
    printf "restore_command = '/bin/false'\n" >> "$w/data/postgresql.auto.conf"
    say "  $name: $PG_USER cannot read the disk; recovery uses the WAL inside the backup (archive-copy=y)" >&3
  else chown -R "$PG_USER" "$w/log" "$w/lock" "$w/spool" "$conf"; fi   # the cipher pass stays 0600
  chown -R "$PG_USER" "$w/data" "$w/pg" "$w/sock"; chmod 0700 "$w/data"
  chmod 0711 "$WORK" "$w"
  say "  $name: starting PostgreSQL $v (no network, socket only) ..." >&3
  PGPID_DIR=$w/pg
  if ! nonet runuser -u "$PG_USER" -- "$PGBIN/pg_ctl" -D "$w/pg" -l "$w/pg/server.log" -w -t 1800 start >/dev/null 2>&1; then
    say "  $name: PostgreSQL did not start: $(tail -3 "$w/pg/server.log" 2>/dev/null | tr '\n' ' ')" >&3; PGPID_DIR=""; return 1
  fi
  if ! out=$(runuser -u "$PG_USER" -- "$PGBIN/psql" -X -A -t -h "$w/sock" -p 5439 -d postgres -c 'SELECT 1' 2>&1) || [ "$(tr -d ' \n' <<< "$out")" != 1 ]; then
    say "  $name: SELECT 1 failed: $out" >&3; pg_stop; return 1
  fi
  say "  $name: PostgreSQL opened, SELECT 1 ok" >&3
  if [ -n "$PG_QUERY" ]; then
    say "  $name: your query:" >&3
    if ! runuser -u "$PG_USER" -- "$PGBIN/psql" -X -v ON_ERROR_STOP=1 -h "$w/sock" -p 5439 -d postgres -c "$PG_QUERY" >&3 2>&1; then
      say "  $name: the query FAILED" >&3; pg_stop; return 1
    fi
  fi
  pg_stop
  echo acildi
}

# --- borg ---
drill_borg() {   # drill_borg <repo> <name>
  local repo=$1 name=$2 w=$WORK/$2 last out
  command -v borg >/dev/null || { say "  $name: borg is not installed on this machine" >&3; return 1; }
  install -d -m 0700 "$w" "$w/base" "$w/out"
  BORG_PASSPHRASE=$(ask_secret "$name: borg passphrase (empty: none)" "$BORG_PASS_FILE")
  export BORG_PASSPHRASE BORG_BASE_DIR=$w/base BORG_RELOCATED_REPO_ACCESS_IS_OK=yes BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK=yes
  # the disk is read-only: no lock files in the repository, no cache kept
  if ! last=$(nonet borg --bypass-lock list --short --last 1 "$repo" 2>&1) || [ -z "$last" ]; then
    say "  $name: borg list FAILED: $(tail -2 <<< "$last" | tr '\n' ' ')" >&3; unset BORG_PASSPHRASE; return 1
  fi
  last=$(tail -1 <<< "$last")
  if [ -n "$BORG_PATH" ]; then
    say "  $name: extracting $BORG_PATH from $last ..." >&3
    if out=$(cd "$w/out" && nonet borg --bypass-lock extract "$repo::$last" "$BORG_PATH" 2>&1); then
      say "  $name: extracted $(find "$w/out" -type f | wc -l) files" >&3; unset BORG_PASSPHRASE; echo cikarildi; return 0
    fi
  else
    say "  $name: reading the whole archive $last (extract --dry-run: every chunk read and decrypted) ..." >&3
    if out=$(cd "$w/out" && nonet borg --bypass-lock extract --dry-run "$repo::$last" 2>&1); then
      say "  $name: archive $last read in full" >&3; unset BORG_PASSPHRASE; echo okundu; return 0
    fi
  fi
  unset BORG_PASSPHRASE
  say "  $name: borg extract FAILED: $(tail -2 <<< "$out" | tr '\n' ' ')" >&3; return 1
}

# --- restic ---
drill_restic() {   # drill_restic <repo> <name>
  local repo=$1 name=$2 w=$WORK/$2 out
  command -v restic >/dev/null || { say "  $name: restic is not installed on this machine" >&3; return 1; }
  install -d -m 0700 "$w" "$w/cache" "$w/out"
  RESTIC_PASSWORD=$(ask_secret "$name: restic password" "$RESTIC_PASS_FILE"); export RESTIC_PASSWORD
  export RESTIC_CACHE_DIR=$w/cache
  say "  $name: restic check ..." >&3
  if ! out=$(nonet restic --no-lock -r "$repo" check 2>&1); then
    say "  $name: restic check FAILED: $(tail -2 <<< "$out" | tr '\n' ' ')" >&3; unset RESTIC_PASSWORD; return 1
  fi
  say "  $name: restoring the newest snapshot ..." >&3
  if ! out=$(nonet restic --no-lock -r "$repo" restore latest --target "$w/out" 2>&1); then
    say "  $name: restic restore FAILED: $(tail -2 <<< "$out" | tr '\n' ' ')" >&3; unset RESTIC_PASSWORD; return 1
  fi
  unset RESTIC_PASSWORD
  say "  $name: restored $(find "$w/out" -type f | wc -l) files" >&3
  echo denetlendi
}

write_mark() {   # write_mark <id> <results>
  local id=$1 res=$2 dir f
  if [ -n "$DISK" ]; then
    close_disk; open_disk rw; G=$ROOT/nesil A=$ROOT/denetim
  elif ! touch "$A/.purser-restore-w" 2>/dev/null; then
    say "The disk is mounted read-only: the mark was not written. To write it, mount the disk read-write and run:"
    say "  install -d -m 0700 $A/iyi && printf 'yol=tatbikat\\nat=%s\\nkaynaklar=%s\\narac=%s\\n' > $A/iyi/$id" "$(date +%s)" "$res" "$VERSION"
    return 1
  fi
  rm -f "$A/.purser-restore-w"
  dir=$A/iyi; install -d -m 0700 "$dir"; f=$dir/$id
  printf 'yol=tatbikat\nat=%s\nkaynaklar=%s\narac=%s\n' "$(date +%s)" "$res" "$VERSION" > "$dir/.$id.tmp" && mv -f "$dir/.$id.tmp" "$f"
  sync
  say "mark written: $id is verified good (drill $(date +%F)). The box shows it and keeps it after its next window."
}

case $ACTION in
  list) list_generations; exit 0 ;;
  copy)
    [[ $SOURCE =~ $NAME_RE ]] || die "--source <name> expected (a directory of the generation)"
    [ -n "$TO" ] || die "--to <dir> expected"
    t=$(tree_of "$GID") || die "no generation $GID on the disk"
    [ -d "$t/$SOURCE" ] || die "generation $GID has no source $SOURCE ($(find "$t" -mindepth 1 -maxdepth 1 -printf '%f ' | sort))"
    suspect_open "$GID" && say "WARNING: $GID is suspect and the suspicion was not cleared at the box"
    install -d -m 0700 "$TO"
    cp -a "$t/$SOURCE" "$TO/" || die "copy failed"
    say "copied $SOURCE of $GID to $TO/$SOURCE; restore it with its tool (docs/restore.md)"
    exit 0 ;;
esac

# --- the drill ---
t=$(tree_of "$GID") || die "no generation $GID on the disk"
long=0; [[ $t == */uzun-* ]] && long=1
if [ -z "$WORK" ]; then WORK=$(mktemp -d /var/tmp/purser-drill.XXXXXX)
else install -d -m 0700 "$WORK"; [ -z "$(ls -A "$WORK")" ] || die "$WORK is not empty"; fi
: > "$WORK/.purser-restore"; chmod 0700 "$WORK"
say "NOQ Purser $VERSION: restore drill of $GID ($([ $long = 1 ] && echo weekly/monthly copy || echo daily))"
sus=0; if suspect_open "$GID"; then sus=1; say "NOTE: $GID is suspect and was not cleared at the box: it is drilled, but it will not be marked."; fi
fail=0 results=()
listok=0
if [ "$LISTCHECK" = 1 ]; then if list_check "$t" "$GID"; then listok=1; else fail=1; fi; fi
exec 3>&1
for d in "$t"/*/; do
  d=${d%/}; name=${d##*/}
  [[ $name =~ $NAME_RE ]] || { say "  skipped: a name outside the alphabet"; fail=1; continue; }
  k=$(kind_of "$d")
  case $k in
    pgbackrest) r=$(drill_pgbackrest "$d" "$name" "$long") ;;
    borg) r=$(drill_borg "$d" "$name") ;;
    restic) r=$(drill_restic "$d" "$name") ;;
    *) if [ "$LISTCHECK" = 0 ]; then say "  $name: plain directory, not checked (--no-list-check): the drill cannot pass"; r=""
       elif [ "$listok" = 1 ]; then say "  $name: plain directory, matches its list"; r=eslesti
       else say "  $name: plain directory, its list does not match"; r=""; fi ;;
  esac
  r=$(tail -1 <<< "$r")
  if [[ $r =~ ^[a-z_]{1,20}$ ]]; then results+=("$name:$r"); else fail=1; results+=("$name:hata"); fi
done
exec 3>&-
[ ${#results[@]} -gt 0 ] || { say "the generation holds no source"; fail=1; }
res=$(IFS=,; printf '%s' "${results[*]}")
say ""
if [ "$fail" = 0 ]; then
  say "DRILL PASSED: $GID ($res)"
  if [ "$MARK" = 0 ]; then say "no mark written (--no-mark)"
  elif [ "$sus" = 1 ]; then say "no mark written: the generation is suspect and not cleared"
  else write_mark "$GID" "$res" || true; fi
  exit 0
fi
say "DRILL FAILED: $GID ($res). No mark written. Keep the disk as it is and look at the messages above."
exit 1
