#!/usr/bin/env bash

set -Eeuo pipefail
umask 077
export LANG=C

EXPECTED_HOSTNAME="sqjcredis01"
EXPECTED_IPV4="10.2.203.112"
EXPECTED_OS="openEuler release 24.03 (LTS-SP1)"
EXPECTED_ARCH="x86_64"
EXPECTED_Q072_RUN_ID="q072-20260727T170054+0800"
EXPECTED_Q072_ARCHIVE_SHA256="8172a0d28a6424b27c623a93ea45e1f0c430ec95bf734b9b7d17ce4723ec34c0"
EXPECTED_FRAMEWORK_BUNDLE_SHA256="c0f6304dc0e03024a05ea5de17d00be58a7f1af447cd50b4330a2796b54e4d8a"

BUNDLE_ROOT="/opt/zhct-deploy"
FRAMEWORK_ARCHIVE="/root/redis01-q073-framework-c0f6304d.tar.gz"
Q072_EVIDENCE="/var/backups/zhct-q072/${EXPECTED_Q072_RUN_ID}"
Q072_RESULT="${Q072_EVIDENCE}/result.env"
Q072_ARCHIVE="/root/redis01-q072-evidence-${EXPECTED_Q072_RUN_ID}.tar.gz"
EVIDENCE_ROOT="/var/backups/zhct-q073"
RUN_ID=${1:-}
MODE=${2:-}
EVIDENCE_DIR="${EVIDENCE_ROOT}/${RUN_ID}"
FINAL_RESULT="${EVIDENCE_DIR}/result.env"
FINAL_INDEX="${EVIDENCE_DIR}/evidence-index.sha256"
FINAL_ARCHIVE="/root/redis01-q073-evidence-${RUN_ID}.tar.gz"
STAGE_DIR=
SEAL_ATTEMPTED=0
SEAL_COMPLETED=0
TARGET_PORT_RE=':(6379|6387|26379|26387|3000|10008|16379|16387|36379|36387)([[:space:]]|$)'

TARGET_UNITS=(
  redis5.service
  redis7.service
  sentinel5.service
  sentinel7.service
  orchestrator.service
)

REDIS_UNITS=(
  redis5.service
  redis7.service
  sentinel5.service
  sentinel7.service
)

FORMAL_BINARIES=(
  /opt/redis/5.0.14/bin/redis-server
  /opt/redis/5.0.14/bin/redis-cli
  /opt/redis/5.0.14/bin/redis-sentinel
  /opt/redis/7.2.14/bin/redis-server
  /opt/redis/7.2.14/bin/redis-cli
  /opt/redis/7.2.14/bin/redis-sentinel
  /usr/local/orchestrator/orchestrator
  /usr/bin/orchestrator
  /usr/bin/orchestrator-client
)

STATE_DIRS=(
  /data/redis5
  /data/redis7
  /var/lib/redis-sentinel5
  /var/lib/redis-sentinel7
)

LOG_DIRS=(
  /var/log/redis5
  /var/log/redis7
  /var/log/redis-sentinel5
  /var/log/redis-sentinel7
)

die() {
  printf 'ERROR: %s\n' "$*" >&2
  exit 1
}

on_exit() {
  local rc=$?
  set +e
  [[ -z "${STAGE_DIR}" ]] || rm -rf -- "${STAGE_DIR}"
  if [[ "${rc}" -ne 0 && -d "${EVIDENCE_DIR}" ]]; then
    {
      printf 'failed_at=%s\n' "$(date --iso-8601=seconds)"
      printf 'exit_code=%s\n' "${rc}"
      printf 'seal_attempted=%s\n' "${SEAL_ATTEMPTED}"
      printf 'seal_completed=%s\n' "${SEAL_COMPLETED}"
      printf 'services_must_remain_quiescent=YES\n'
      printf 'automatic_rerun=FORBIDDEN\n'
      printf 'automatic_identity_restore=FORBIDDEN\n'
    } >"${EVIDENCE_DIR}/failure.env"
    chmod 0600 "${EVIDENCE_DIR}/failure.env"
  fi
  trap - EXIT
  exit "${rc}"
}
trap on_exit EXIT

capture() {
  local name=$1
  shift
  {
    printf '# captured_at=%s\n' "$(date --iso-8601=seconds)"
    printf '# command='
    printf '%q ' "$@"
    printf '\n'
    "$@"
  } >"${EVIDENCE_DIR}/${name}.txt" 2>&1
}

capture_shell() {
  local name=$1
  local command=$2
  {
    printf '# captured_at=%s\n' "$(date --iso-8601=seconds)"
    printf '# command=%s\n' "${command}"
    bash -Eeuo pipefail -c "${command}"
  } >"${EVIDENCE_DIR}/${name}.txt" 2>&1
}

assert_file_sha256() {
  local path=$1
  local expected=$2
  [[ -f "${path}" && ! -L "${path}" ]] || die "required regular file is missing or unsafe: ${path}"
  [[ "$(sha256sum "${path}" | awk '{print $1}')" == "${expected}" ]] || die "SHA256 mismatch: ${path}"
}

assert_result_line() {
  local file=$1
  local line=$2
  grep -Fxq "${line}" "${file}" || die "required result line is missing: ${line}"
}

assert_snapshot_unchanged() {
  local before=$1
  local after=$2
  local label=$3
  cmp -s <(sed -n '3,$p' "${before}") <(sed -n '3,$p' "${after}") || die "${label} changed during seal"
}

capture_units() {
  local output=$1
  : >"${output}"
  local unit load enabled active substate
  for unit in "${TARGET_UNITS[@]}"; do
    load=$(systemctl show "${unit}" -p LoadState --value 2>/dev/null || true)
    enabled=$(systemctl is-enabled "${unit}" 2>/dev/null || true)
    active=$(systemctl show "${unit}" -p ActiveState --value 2>/dev/null || true)
    substate=$(systemctl show "${unit}" -p SubState --value 2>/dev/null || true)
    printf '%s\t%s\t%s\t%s\t%s\n' "${unit}" "${load}" "${enabled}" "${active}" "${substate}" >>"${output}"
  done
}

assert_units_quiescent() {
  local output=$1
  capture_units "${output}"
  local unit load enabled active substate
  while IFS=$'\t' read -r unit load enabled active substate; do
    [[ "${load}" == "loaded" ]] || die "unit is not loaded: ${unit}"
    [[ "${enabled}" == "disabled" ]] || die "unit is not disabled: ${unit}"
    [[ "${active}" == "inactive" ]] || die "unit is not inactive: ${unit}"
    [[ "${substate}" == "dead" ]] || die "unit is not dead: ${unit}"
  done <"${output}"
}

assert_no_role_processes() {
  local output=$1
  ps -eo pid=,comm=,args= | awk -v self="$$" '
    $1 != self &&
    ($2 ~ /^(redis-server|redis-sentinel|orchestrator)$/ ||
     $0 ~ /\/var\/tmp\/zhct-q072-/ ||
     $0 ~ /\/var\/tmp\/zhct-redis-(build|stage)-/) {print}
  ' >"${output}"
  [[ ! -s "${output}" ]] || die "Redis/Orchestrator/Q072 build process remains"
}

assert_no_target_listeners() {
  local output=$1
  ss -lntupH >"${output}"
  ! grep -Eq "${TARGET_PORT_RE}" "${output}" || die "target listener remains"
}

assert_state_empty() {
  local output=$1
  : >"${output}"
  local path
  for path in "${STATE_DIRS[@]}"; do
    [[ -d "${path}" && ! -L "${path}" ]] || die "state directory is missing or unsafe: ${path}"
    find "${path}" -mindepth 1 -printf '%y\t%p\n' | sort >>"${output}"
    ! find "${path}" -mindepth 1 -print -quit | grep -q . || die "formal Redis/Sentinel state remains: ${path}"
  done
  for path in /var/lib/orchestrator/.raft /var/lib/orchestrator/raft /var/lib/orchestrator/orchestrator.db; do
    [[ ! -e "${path}" && ! -L "${path}" ]] || die "formal Orchestrator state remains: ${path}"
  done
}

assert_logs_empty() {
  local output=$1
  : >"${output}"
  local path
  for path in "${LOG_DIRS[@]}"; do
    [[ -d "${path}" && ! -L "${path}" ]] || die "log directory is missing or unsafe: ${path}"
    find "${path}" -mindepth 1 -printf '%y\t%p\n' | sort >>"${output}"
    ! find "${path}" -mindepth 1 -type f -print -quit | grep -q . || die "Redis/Sentinel log file remains: ${path}"
  done
}

assert_runtime_config_absent() {
  local output=$1
  : >"${output}"
  local path state
  for path in \
    /etc/zhct/node.env /etc/zhct/secrets \
    /etc/redis/redis5.conf /etc/redis/redis7.conf \
    /var/lib/redis-sentinel5/sentinel.conf \
    /var/lib/redis-sentinel7/sentinel.conf \
    /etc/orchestrator.conf.json; do
    state=ABSENT
    [[ ! -e "${path}" && ! -L "${path}" ]] || state=PRESENT
    printf '%s\t%s\n' "${path}" "${state}" >>"${output}"
    [[ "${state}" == "ABSENT" ]] || die "rendered config, identity or secret remains: ${path}"
  done
}

assert_space_gate() {
  local output=$1
  local available total percent
  available=$(df -PB1 / | awk 'NR == 2 {print $4}')
  total=$(df -PB1 / | awk 'NR == 2 {print $2}')
  percent=$((available * 100 / total))
  {
    printf 'root_available_bytes=%s\n' "${available}"
    printf 'root_total_bytes=%s\n' "${total}"
    printf 'root_available_percent=%s\n' "${percent}"
    printf 'minimum_available_percent=20\n'
  } >"${output}"
  [[ "${percent}" -ge 20 ]] || die "root free percentage below 20% gate"
}

assert_preseal_identity_present() {
  local output=$1
  [[ -f /etc/machine-id && ! -L /etc/machine-id && -s /etc/machine-id ]] || die "machine-id is missing, unsafe or already empty before seal"
  find /etc/ssh -maxdepth 1 -type f -name 'ssh_host_*_key*' -printf '%f\n' | sort >"${output}"
  [[ -s "${output}" ]] || die "no SSH host keys found before seal"
  if grep -Ev '^(ssh_host_(ecdsa|ed25519|rsa)_key)(\.pub)?$' "${output}" | grep -q .; then
    die "unexpected SSH host key type would survive canonical seal"
  fi
}

assert_clone_identity_removed() {
  local output=$1
  local machine_size key_count
  [[ -f /etc/machine-id && ! -L /etc/machine-id ]] || die "/etc/machine-id is missing or unsafe"
  machine_size=$(stat -c '%s' /etc/machine-id)
  [[ "${machine_size}" -eq 0 ]] || die "/etc/machine-id is not empty"
  [[ ! -e /var/lib/dbus/machine-id && ! -L /var/lib/dbus/machine-id ]] || die "DBus machine-id remains"
  key_count=$(find /etc/ssh -maxdepth 1 -type f -name 'ssh_host_*_key*' -print | wc -l)
  [[ "${key_count}" -eq 0 ]] || die "SSH host key remains"
  {
    printf 'etc_machine_id_bytes=%s\n' "${machine_size}"
    printf 'dbus_machine_id=ABSENT\n'
    printf 'ssh_host_key_file_count=%s\n' "${key_count}"
  } >"${output}"
}

assert_framework_exact() {
  local output=$1
  (
    cd "${STAGE_DIR}"
    find common roles/redis -type f -print0 | sort -z | xargs -0 sha256sum
  ) >"${EVIDENCE_DIR}/framework-files-source.sha256"
  (
    cd "${BUNDLE_ROOT}"
    find common roles/redis -type f -print0 | sort -z | xargs -0 sha256sum
  ) >"${output}"
  cmp -s "${EVIDENCE_DIR}/framework-files-source.sha256" "${output}" || die "installed framework differs from locked bundle"
}

[[ "${EUID}" -eq 0 ]] || die "must run as root"
[[ "${MODE}" == "--execute-q073-seal" ]] || die "explicit --execute-q073-seal is required"
[[ "${RUN_ID}" =~ ^q073-[0-9]{8}T[0-9]{6}\+0800$ ]] || die "invalid Q073 run id"
[[ "$(hostname -s)" == "${EXPECTED_HOSTNAME}" ]] || die "hostname mismatch"
[[ "$(tr -d '\r' </etc/openEuler-release)" == "${EXPECTED_OS}" ]] || die "OS mismatch"
[[ "$(uname -m)" == "${EXPECTED_ARCH}" ]] || die "architecture mismatch"
ip -o -4 addr show scope global | awk '{print $4}' | cut -d/ -f1 | grep -Fxq "${EXPECTED_IPV4}" || die "expected IPv4 is not configured"

for command in awk bash chmod chown cmp cp cut date df dnf find getent grep hostname \
  install ip pgrep ps rpm sed sha256sum sort ssh-keygen ss stat systemctl tar tr uname wc xargs; do
  command -v "${command}" >/dev/null 2>&1 || die "required command is missing: ${command}"
done

[[ ! -e "${EVIDENCE_DIR}" && ! -L "${EVIDENCE_DIR}" ]] || die "Q073 evidence run exists"
[[ ! -e "${FINAL_ARCHIVE}" && ! -L "${FINAL_ARCHIVE}" ]] || die "Q073 archive exists"
install -d -m 0700 "${EVIDENCE_ROOT}" "${EVIDENCE_DIR}"
cp -a "$0" "${EVIDENCE_DIR}/q073-seal-redis01.sh"
chmod 0600 "${EVIDENCE_DIR}/q073-seal-redis01.sh"

[[ -f "${Q072_RESULT}" && ! -L "${Q072_RESULT}" ]] || die "Q072 result is missing"
for line in \
  "run_id=${EXPECTED_Q072_RUN_ID}" \
  "network_namespace=NO_ROUTES" \
  "offline_rpm_reinstall_assumeno=PASS" \
  "offline_redis5_rebuild_cflags=-fwrapv" \
  "offline_redis7_rebuild_cflags=DEFAULT" \
  "installed_rpm_set_unchanged=PASS" \
  "dnf_history_unchanged=PASS" \
  "installed_runtime_sha256_unchanged=PASS" \
  "target_units=INACTIVE" \
  "target_listeners=NONE" \
  "q072=PASS"; do
  assert_result_line "${Q072_RESULT}" "${line}"
done
assert_file_sha256 "${Q072_ARCHIVE}" "${EXPECTED_Q072_ARCHIVE_SHA256}"
assert_file_sha256 "${FRAMEWORK_ARCHIVE}" "${EXPECTED_FRAMEWORK_BUNDLE_SHA256}"
cp -a "${Q072_RESULT}" "${EVIDENCE_DIR}/q072-result-copy.env"
sha256sum "${Q072_ARCHIVE}" "${FRAMEWORK_ARCHIVE}" >"${EVIDENCE_DIR}/input-archives.sha256"

getent passwd redis >/dev/null || die "redis account is missing"
[[ "$(getent passwd redis | awk -F: '{print $7}')" == "/sbin/nologin" ]] || die "redis account is not nologin"
for package in jq oniguruma percona-orchestrator percona-orchestrator-cli percona-orchestrator-client; do
  rpm -q "${package}" >/dev/null || die "installed package is missing: ${package}"
done
for binary in "${FORMAL_BINARIES[@]}"; do
  [[ -x "${binary}" ]] || die "formal executable is missing: ${binary}"
done
/opt/redis/5.0.14/bin/redis-server --version | grep -Fq 'v=5.0.14' || die "Redis5 version mismatch"
/opt/redis/7.2.14/bin/redis-server --version | grep -Fq 'v=7.2.14' || die "Redis7 version mismatch"
[[ "$(sysctl -n vm.overcommit_memory)" == "1" ]] || die "vm.overcommit_memory is not 1"
grep -Fq '[never]' /sys/kernel/mm/transparent_hugepage/enabled || die "THP is not disabled"
[[ "$(systemctl is-enabled zhct-redis-thp.service)" == "enabled" ]] || die "THP unit is not enabled"
[[ "$(systemctl is-active zhct-redis-thp.service)" == "active" ]] || die "THP unit is not active"

capture hostname-before hostnamectl
capture ipv4-before ip -4 -br addr
capture routes-before ip route show table all
capture dnf-history-before dnf history list
capture_shell dnf-history-ids-before "dnf history list | awk '\$1 ~ /^[0-9]+$/ {print \$1}'"
capture filesystems-before df -hT
capture binaries-before sha256sum "${FORMAL_BINARIES[@]}"
capture_units "${EVIDENCE_DIR}/units-before.tsv"
assert_no_role_processes "${EVIDENCE_DIR}/role-processes-before.txt"
assert_no_target_listeners "${EVIDENCE_DIR}/listeners-before.txt"
assert_runtime_config_absent "${EVIDENCE_DIR}/runtime-config-before.tsv"
assert_space_gate "${EVIDENCE_DIR}/space-before.env"
assert_preseal_identity_present "${EVIDENCE_DIR}/ssh-host-key-files-before.txt"
find /etc/ssh -maxdepth 1 -type f -name 'ssh_host_*.pub' -print0 | sort -z | \
  xargs -0 -r -n 1 ssh-keygen -lf >"${EVIDENCE_DIR}/ssh-host-public-fingerprints-before.txt"

for path in "${BUNDLE_ROOT}/common" "${BUNDLE_ROOT}/roles/redis" /etc/zhct/templates/redis; do
  [[ ! -e "${path}" && ! -L "${path}" ]] || die "refuse to overwrite pre-existing path: ${path}"
done
for unit in "${REDIS_UNITS[@]}"; do
  [[ ! -e "/etc/systemd/system/${unit}" && ! -L "/etc/systemd/system/${unit}" ]] || die "refuse to overwrite pre-existing unit: ${unit}"
done

STAGE_DIR=$(mktemp -d /var/tmp/zhct-q073-framework.XXXXXX)
tar -xzf "${FRAMEWORK_ARCHIVE}" -C "${STAGE_DIR}"
[[ -d "${STAGE_DIR}/common" && -d "${STAGE_DIR}/roles/redis" ]] || die "framework archive layout is invalid"
! find "${STAGE_DIR}" -type l -print -quit | grep -q . || die "framework archive contains symbolic links"
! find "${STAGE_DIR}" -name '._*' -o -name '.DS_Store' | grep -q . || die "framework archive contains metadata files"

install -d -o root -g root -m 0750 "${BUNDLE_ROOT}/common" "${BUNDLE_ROOT}/roles/redis"
cp -a "${STAGE_DIR}/common/." "${BUNDLE_ROOT}/common/"
cp -a "${STAGE_DIR}/roles/redis/." "${BUNDLE_ROOT}/roles/redis/"
chown -R root:root "${BUNDLE_ROOT}/common" "${BUNDLE_ROOT}/roles/redis"
assert_framework_exact "${EVIDENCE_DIR}/framework-files-installed.sha256"
capture_shell framework-bash-syntax \
  "for file in '${BUNDLE_ROOT}/common/scripts/seal-template.sh' '${BUNDLE_ROOT}/common/scripts/post-clone.sh' '${BUNDLE_ROOT}/common/bin/role-action.sh' '${BUNDLE_ROOT}/common/lib/runtime.sh' '${BUNDLE_ROOT}/roles/redis/hooks.sh'; do bash -n \"\${file}\"; done"

install -d -o root -g root -m 0750 /etc/zhct/templates
cp -a "${BUNDLE_ROOT}/roles/redis/templates" /etc/zhct/templates/redis
chown -R root:root /etc/zhct/templates/redis
find /etc/zhct/templates/redis -type d -exec chmod 0750 {} +
find /etc/zhct/templates/redis -type f -exec chmod 0640 {} +

install -d -o root -g redis -m 0750 /etc/redis
for path in "${STATE_DIRS[@]}" "${LOG_DIRS[@]}"; do
  install -d -o redis -g redis -m 0750 "${path}"
done
for unit in "${REDIS_UNITS[@]}"; do
  install -o root -g root -m 0644 \
    "${BUNDLE_ROOT}/roles/redis/templates/systemd/${unit}" \
    "/etc/systemd/system/${unit}"
done
systemctl daemon-reload
for unit in "${TARGET_UNITS[@]}"; do
  systemctl disable --now "${unit}" >/dev/null 2>&1 || true
done
assert_units_quiescent "${EVIDENCE_DIR}/units-staged.tsv"
assert_no_role_processes "${EVIDENCE_DIR}/role-processes-staged.txt"
assert_no_target_listeners "${EVIDENCE_DIR}/listeners-staged.txt"
assert_state_empty "${EVIDENCE_DIR}/formal-state-staged.tsv"
assert_logs_empty "${EVIDENCE_DIR}/logs-staged.tsv"
assert_runtime_config_absent "${EVIDENCE_DIR}/runtime-config-staged.tsv"

capture template-files-sha256 sha256sum \
  /etc/zhct/templates/redis/nodes/redis01/redis5.conf \
  /etc/zhct/templates/redis/nodes/redis01/redis7.conf \
  /etc/zhct/templates/redis/nodes/redis01/sentinel5.conf \
  /etc/zhct/templates/redis/nodes/redis01/sentinel7.conf \
  /etc/zhct/templates/redis/nodes/redis01/orchestrator.conf.json \
  /etc/zhct/templates/redis/nodes/redis02/redis5.conf \
  /etc/zhct/templates/redis/nodes/redis02/redis7.conf \
  /etc/zhct/templates/redis/nodes/redis02/sentinel5.conf \
  /etc/zhct/templates/redis/nodes/redis02/sentinel7.conf \
  /etc/zhct/templates/redis/nodes/redis02/orchestrator.conf.json
capture unit-files-sha256 sha256sum \
  /etc/systemd/system/redis5.service \
  /etc/systemd/system/redis7.service \
  /etc/systemd/system/sentinel5.service \
  /etc/systemd/system/sentinel7.service

capture seal-dry-run env RUN_ID="${RUN_ID}-dry" \
  bash "${BUNDLE_ROOT}/common/scripts/seal-template.sh" \
  --role redis --bundle-root "${BUNDLE_ROOT}" --dry-run
capture post-clone-dry-run env RUN_ID="${RUN_ID}-post-clone-dry" \
  bash "${BUNDLE_ROOT}/common/scripts/post-clone.sh" \
  --role redis --node redis01 --expected-ip "${EXPECTED_IPV4}" \
  --bundle-root "${BUNDLE_ROOT}" --dry-run

SEAL_ATTEMPTED=1
capture seal-live env RUN_ID="${RUN_ID}" \
  bash "${BUNDLE_ROOT}/common/scripts/seal-template.sh" \
  --role redis --bundle-root "${BUNDLE_ROOT}" --confirm-seal
SEAL_COMPLETED=1

assert_units_quiescent "${EVIDENCE_DIR}/units-after.tsv"
assert_no_role_processes "${EVIDENCE_DIR}/role-processes-after.txt"
assert_no_target_listeners "${EVIDENCE_DIR}/listeners-after.txt"
assert_state_empty "${EVIDENCE_DIR}/formal-state-after.tsv"
assert_logs_empty "${EVIDENCE_DIR}/logs-after.tsv"
assert_runtime_config_absent "${EVIDENCE_DIR}/runtime-config-after.tsv"
assert_clone_identity_removed "${EVIDENCE_DIR}/clone-identity-after.env"
assert_space_gate "${EVIDENCE_DIR}/space-after.env"

capture ipv4-after ip -4 -br addr
capture routes-after ip route show table all
capture dnf-history-after dnf history list
capture_shell dnf-history-ids-after "dnf history list | awk '\$1 ~ /^[0-9]+$/ {print \$1}'"
capture filesystems-after df -hT
capture binaries-after sha256sum "${FORMAL_BINARIES[@]}"

assert_snapshot_unchanged "${EVIDENCE_DIR}/ipv4-before.txt" "${EVIDENCE_DIR}/ipv4-after.txt" "IPv4"
assert_snapshot_unchanged "${EVIDENCE_DIR}/routes-before.txt" "${EVIDENCE_DIR}/routes-after.txt" "routes"
assert_snapshot_unchanged "${EVIDENCE_DIR}/dnf-history-ids-before.txt" "${EVIDENCE_DIR}/dnf-history-ids-after.txt" "DNF history"
assert_snapshot_unchanged "${EVIDENCE_DIR}/binaries-before.txt" "${EVIDENCE_DIR}/binaries-after.txt" "formal binaries"

find "${EVIDENCE_DIR}" -type f \( -name '*.pem' -o -name '*.key' -o -name 'ssh_host_*' \) -print >"${EVIDENCE_DIR}/forbidden-private-files.txt"
[[ ! -s "${EVIDENCE_DIR}/forbidden-private-files.txt" ]] || die "private key-like evidence found"
printf 'PASS\n' >"${EVIDENCE_DIR}/sensitive-scan.txt"

{
  printf 'run_id=%s\n' "${RUN_ID}"
  printf 'completed_at=%s\n' "$(date --iso-8601=seconds)"
  printf 'q072_run_id=%s\n' "${EXPECTED_Q072_RUN_ID}"
  printf 'q072_evidence_gate=PASS\n'
  printf 'framework_stage=PASS\n'
  printf 'redis_template_files=PASS\n'
  printf 'preseal_quiescence=PASS\n'
  printf 'seal_dry_run=PASS\n'
  printf 'post_clone_dry_run=PASS\n'
  printf 'live_seal=PASS\n'
  printf 'clone_identity_removed=PASS\n'
  printf 'formal_redis_sentinel_state_entries=0\n'
  printf 'formal_orchestrator_state=ABSENT\n'
  printf 'target_listener_count=0\n'
  printf 'role_process_count=0\n'
  printf 'machine_id_bytes=0\n'
  printf 'ssh_host_key_file_count=0\n'
  printf 'root_available_percent_gate=PASS_GE_20\n'
  printf 'reboot_persistence_verification=WAIVED_BY_USER_NOT_EXECUTED\n'
  printf 'service_activation=NOT_PERFORMED\n'
  printf 'post_clone_execution=NOT_PERFORMED\n'
  printf 'template_state=SEALED_AWAITING_CUSTOMER_APPLICATION\n'
  printf 'guest_reboot_or_reconnect=FORBIDDEN\n'
  printf 'next_task=Q130_AFTER_Q122_CUSTOMER_TEMPLATE_APPLICATION\n'
  printf 'q073=PASS\n'
} >"${FINAL_RESULT}"
chmod 0600 "${FINAL_RESULT}"

find "${EVIDENCE_DIR}" -type l -print >"${EVIDENCE_DIR}/symlinks.txt"
[[ ! -s "${EVIDENCE_DIR}/symlinks.txt" ]] || die "evidence contains a symbolic link"
(
  cd "${EVIDENCE_DIR}"
  find . -type f ! -name 'evidence-index.sha256' -print0 | sort -z | \
    xargs -0 sha256sum >"$(basename "${FINAL_INDEX}")"
)
chmod 0600 "${FINAL_INDEX}"
(
  cd "${EVIDENCE_ROOT}"
  tar -czf "${FINAL_ARCHIVE}" "${RUN_ID}"
)
sha256sum "${FINAL_ARCHIVE}" >"${FINAL_ARCHIVE}.sha256"
chmod 0600 "${FINAL_ARCHIVE}" "${FINAL_ARCHIVE}.sha256"

rm -f -- "${FRAMEWORK_ARCHIVE}"
rm -f -- "$0"
printf 'Q073_REDIS01_TEMPLATE_SEAL_OK\n'
printf 'run_id=%s\n' "${RUN_ID}"
printf 'evidence=%s\n' "${EVIDENCE_DIR}"
printf 'archive=%s\n' "${FINAL_ARCHIVE}"
printf 'archive_sha256=%s\n' "$(awk '{print $1}' "${FINAL_ARCHIVE}.sha256")"
printf 'template_state=SEALED_AWAITING_CUSTOMER_APPLICATION\n'
printf 'DO_NOT_REBOOT_RECONNECT_OR_RUN_MORE_COMMANDS\n'
