#!/usr/bin/env bash

set -Eeuo pipefail
umask 077
export LANG=C

EXPECTED_HOSTNAME="sqjcnginx01"
EXPECTED_IPV4="10.2.203.102"
EXPECTED_OS="openEuler release 24.03 (LTS-SP1)"
EXPECTED_ARCH="x86_64"
EXPECTED_Q042_RUN_ID="q042-20260723T134134+0800-R1"
EXPECTED_Q042_ARCHIVE_SHA256="324085837e239dfc282aaf459fee90248a96e332b8a6ef2f66c6930b53d39aa8"
EXPECTED_SEAL_WRAPPER_SHA256="45171865992b8d8bf94735a889b3f69eefe65707187cf3acb97683bbd69b9e02"
EXPECTED_POST_CLONE_WRAPPER_SHA256="ca5fa0a113739bcbe3ff51b2815bb50723cd8b1cf33dfb6d3f3f172caf2dabc6"
EXPECTED_ROLE_ACTION_SHA256="e3eae16aa5c87f43b56495fc71de378a947578cabe18b507e8fed01ac1f32025"
EXPECTED_RUNTIME_SHA256="89e5149c516af624dd56b3ef8aaa389a4f2447a68dfe989978c61c459d859162"
EXPECTED_NGINX_HOOKS_SHA256="52c3261326cd09781b7cef59fe89e1ffa67a6bb40a316ddfc09bd43c5ce246bf"
EXPECTED_ROLE_ENV_SHA256="515e68791bd62b760e6dd5707d0579dd03ababcb51afbcc90903c69836e37f6d"
EXPECTED_UNITS_SHA256="98bec522fafb6d91f6be7f2bffeb40353b5b07882a82982b67c400d05cc4bc34"
EXPECTED_NODES_SHA256="ce18e7febc7e3105294ddc74d32f10f7fb4da2c4d8e59c3e9642816ec770463f"

BUNDLE_ROOT="/opt/zhct-deploy"
SEAL_SCRIPT="${BUNDLE_ROOT}/common/scripts/seal-template.sh"
POST_CLONE_SCRIPT="${BUNDLE_ROOT}/common/scripts/post-clone.sh"
Q042_EVIDENCE="/var/backups/zhct-q042/evidence/${EXPECTED_Q042_RUN_ID}"
Q042_FINAL_RESULT="${Q042_EVIDENCE}/final-audit-result.env"
Q042_ARCHIVE="/root/q042-evidence-${EXPECTED_Q042_RUN_ID}.tar.gz"
EVIDENCE_ROOT="/var/backups/zhct-q043/evidence"
RUN_ID=${1:-}
MODE=${2:-}
EVIDENCE_DIR="${EVIDENCE_ROOT}/${RUN_ID}"
FINAL_RESULT="${EVIDENCE_DIR}/final-result.env"
FINAL_INDEX="${EVIDENCE_DIR}/q043-final-evidence-index.sha256"
FINAL_ARCHIVE="/root/q043-evidence-${RUN_ID}.tar.gz"
SENSITIVE_SCAN_TMP="${EVIDENCE_ROOT}/.${RUN_ID}.sensitive-scan.tmp"
MIN_FREE_BYTES=$((9 * 1024 * 1024 * 1024))
VIP_RE='10\.2\.203\.(115|116|117)'
TARGET_PORT_RE=':(8081|8443|3306|3308|6379|6387|1883|8083|3000|26379|26387)([[:space:]]|$)'
CREATED_COMPAT_LOG_DIR=0
SEAL_ATTEMPTED=0
SEAL_COMPLETED=0

TARGET_UNITS=(
  nginx.service
  keepalived.service
  haproxy.service
  orchestrator.service
  sentinel5.service
  sentinel7.service
)

FORMAL_BINARIES=(
  /usr/local/nginx/sbin/nginx
  /usr/local/sbin/keepalived
  /usr/local/haproxy/sbin/haproxy
  /usr/local/orchestrator/orchestrator
  /opt/redis/5.0.14/bin/redis-sentinel
  /opt/redis/5.0.14/bin/redis-cli
  /opt/redis/7.2.14/bin/redis-sentinel
  /opt/redis/7.2.14/bin/redis-cli
  /usr/bin/orchestrator
  /usr/bin/orchestrator-client
)

FORMAL_UNIT_FILES=(
  /etc/systemd/system/nginx.service
  /etc/systemd/system/keepalived.service
  /etc/systemd/system/haproxy.service
  /usr/lib/systemd/system/orchestrator.service
  /etc/systemd/system/sentinel5.service
  /etc/systemd/system/sentinel7.service
)

FORMAL_RUNTIME_PATHS=(
  /etc/keepalived/keepalived.conf
  /etc/haproxy/haproxy.cfg
  /etc/orchestrator.conf.json
  /var/lib/redis-sentinel5/sentinel.conf
  /var/lib/redis-sentinel7/sentinel.conf
  /var/lib/orchestrator/.raft
  /var/lib/orchestrator/raft
  /var/lib/orchestrator/orchestrator.db
  /etc/zhct/node.env
  /etc/zhct/secrets
)

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

cleanup_compat_dir() {
  if [[ "${CREATED_COMPAT_LOG_DIR}" -eq 1 && -d /var/log/zhct ]]; then
    rmdir /var/log/zhct 2>/dev/null || true
  fi
}

on_exit() {
  local rc=$?
  set +e
  cleanup_compat_dir
  rm -f "${SENSITIVE_SCAN_TMP}"
  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_body_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"
}

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_units_quiescent() {
  local output=$1
  : >"${output}"
  local unit enabled active substate started
  for unit in "${TARGET_UNITS[@]}"; do
    enabled=$(systemctl is-enabled "${unit}" 2>/dev/null || true)
    active=$(systemctl show "${unit}" -p ActiveState --value)
    substate=$(systemctl show "${unit}" -p SubState --value)
    started=$(systemctl show "${unit}" -p ExecMainStartTimestampMonotonic --value)
    printf '%s\t%s\t%s\t%s\t%s\n' \
      "${unit}" "${enabled}" "${active}" "${substate}" "${started}" >>"${output}"
    [[ "${enabled}" == "disabled" ]] || die "unit is not disabled: ${unit}"
    [[ "${active}" == "inactive" ]] || die "unit is not inactive: ${unit}"
    [[ "${substate}" == "dead" ]] || die "unit is not dead: ${unit}"
    [[ "${started}" == "0" ]] || die "unit has a start timestamp: ${unit}"
  done
}

assert_runtime_paths_absent() {
  local output=$1
  : >"${output}"
  local path state
  for path in "${FORMAL_RUNTIME_PATHS[@]}"; do
    state=ABSENT
    [[ ! -e "${path}" && ! -L "${path}" ]] || state=PRESENT
    printf '%s\t%s\n' "${path}" "${state}" >>"${output}"
    [[ "${state}" == "ABSENT" ]] || die "formal runtime path remains: ${path}"
  done
}

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

assert_no_vip() {
  local output=$1
  ip -o -4 addr show >"${output}"
  ! grep -Eq "${VIP_RE}" "${output}" || die "VIP remains announced"
}

assert_state_dirs_empty() {
  local output=$1
  : >"${output}"
  local dir count
  for dir in /var/lib/redis-sentinel5 /var/lib/redis-sentinel7; do
    [[ -d "${dir}" && ! -L "${dir}" ]] || die "required Sentinel state directory is missing or unsafe: ${dir}"
    count=$(find "${dir}" -mindepth 1 -print | wc -l)
    printf '%s\t%s\n' "${dir}" "${count}" >>"${output}"
    [[ "${count}" -eq 0 ]] || die "Sentinel state directory is not empty: ${dir}"
  done
}

assert_optional_log_dir_safe_before() {
  local output=$1
  : >"${output}"
  if [[ ! -e /var/log/zhct && ! -L /var/log/zhct ]]; then
    printf '/var/log/zhct\tABSENT\n' >"${output}"
    return
  fi
  [[ -d /var/log/zhct && ! -L /var/log/zhct ]] || die "/var/log/zhct is not a safe directory"
  find /var/log/zhct -mindepth 1 ! -type d ! -type f -print >"${output}"
  [[ ! -s "${output}" ]] || die "/var/log/zhct contains unsafe non-file state"
  find /var/log/zhct -mindepth 1 -printf '%y\t%p\n' >"${output}"
}

assert_optional_log_dir_clean() {
  local output=$1
  : >"${output}"
  if [[ ! -e /var/log/zhct && ! -L /var/log/zhct ]]; then
    printf '/var/log/zhct\tABSENT\n' >"${output}"
    return
  fi
  [[ -d /var/log/zhct && ! -L /var/log/zhct ]] || die "/var/log/zhct is not a safe directory"
  find /var/log/zhct -mindepth 1 ! -type d -print >"${output}"
  [[ ! -s "${output}" ]] || die "/var/log/zhct contains non-directory state after seal"
  printf '/var/log/zhct\tDIRECTORIES_ONLY\n' >"${output}"
}

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_bytes=%s\n' "${MIN_FREE_BYTES}"
    printf 'minimum_available_percent=20\n'
  } >"${output}"
  [[ "${available}" -ge "${MIN_FREE_BYTES}" ]] || die "root free bytes below 9GiB gate"
  [[ "${percent}" -ge 20 ]] || die "root free percentage below 20% gate"
}

assert_preseal_host_keys_expected() {
  local output=$1
  find /etc/ssh -maxdepth 1 -type f -name 'ssh_host_*_key*' -printf '%f\n' | sort >"${output}"
  [[ -s "${output}" ]] || die "no existing 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 the 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 after seal"
  machine_size=$(stat -c '%s' /etc/machine-id)
  [[ "${machine_size}" -eq 0 ]] || die "/etc/machine-id is not empty after seal"
  [[ ! -e /var/lib/dbus/machine-id && ! -L /var/lib/dbus/machine-id ]] || \
    die "DBus machine-id remains after seal"
  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 after seal"
  {
    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}"
}

[[ "${EUID}" -eq 0 ]] || die "must run as root"
[[ "${MODE}" == "--execute-seal" ]] || die "explicit --execute-seal is required"
[[ "${RUN_ID}" =~ ^q043-[0-9]{8}T[0-9]{6}\+0800$ ]] || die "invalid Q043 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 cmp cp cut date df dnf env find grep hostname \
  install ip mkdir readlink rmdir 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 "Q043 evidence run already exists"
[[ ! -e "${FINAL_ARCHIVE}" && ! -L "${FINAL_ARCHIVE}" ]] || die "Q043 archive already exists"
[[ ! -e "${FINAL_ARCHIVE}.sha256" && ! -L "${FINAL_ARCHIVE}.sha256" ]] || \
  die "Q043 archive checksum already exists"
install -d -m 0700 "${EVIDENCE_ROOT}" "${EVIDENCE_DIR}"
cp -a "$0" "${EVIDENCE_DIR}/q043-seal-check.sh"
chmod 0600 "${EVIDENCE_DIR}/q043-seal-check.sh"

assert_file_sha256 "${SEAL_SCRIPT}" "${EXPECTED_SEAL_WRAPPER_SHA256}"
assert_file_sha256 "${POST_CLONE_SCRIPT}" "${EXPECTED_POST_CLONE_WRAPPER_SHA256}"
assert_file_sha256 "${BUNDLE_ROOT}/common/bin/role-action.sh" "${EXPECTED_ROLE_ACTION_SHA256}"
assert_file_sha256 "${BUNDLE_ROOT}/common/lib/runtime.sh" "${EXPECTED_RUNTIME_SHA256}"
assert_file_sha256 "${BUNDLE_ROOT}/roles/nginx/hooks.sh" "${EXPECTED_NGINX_HOOKS_SHA256}"
assert_file_sha256 "${BUNDLE_ROOT}/roles/nginx/role.env" "${EXPECTED_ROLE_ENV_SHA256}"
assert_file_sha256 "${BUNDLE_ROOT}/roles/nginx/manifests/systemd-units.tsv" "${EXPECTED_UNITS_SHA256}"
assert_file_sha256 "${BUNDLE_ROOT}/roles/nginx/manifests/nodes.tsv" "${EXPECTED_NODES_SHA256}"
capture_shell framework-sha256 \
  "sha256sum '${SEAL_SCRIPT}' '${POST_CLONE_SCRIPT}' '${BUNDLE_ROOT}/common/bin/role-action.sh' '${BUNDLE_ROOT}/common/lib/runtime.sh' '${BUNDLE_ROOT}/roles/nginx/hooks.sh' '${BUNDLE_ROOT}/roles/nginx/role.env' '${BUNDLE_ROOT}/roles/nginx/manifests/systemd-units.tsv' '${BUNDLE_ROOT}/roles/nginx/manifests/nodes.tsv'"
capture_shell framework-bash-syntax \
  "for file in '${SEAL_SCRIPT}' '${POST_CLONE_SCRIPT}' '${BUNDLE_ROOT}/common/bin/role-action.sh' '${BUNDLE_ROOT}/common/lib/runtime.sh' '${BUNDLE_ROOT}/roles/nginx/hooks.sh'; do bash -n \"\${file}\"; done"

[[ -f "${Q042_FINAL_RESULT}" && ! -L "${Q042_FINAL_RESULT}" ]] || die "Q042 final result is missing"
assert_result_line "${Q042_FINAL_RESULT}" "final_audit_check=PASS"
assert_result_line "${Q042_FINAL_RESULT}" "target_units_quiescent=PASS"
assert_result_line "${Q042_FINAL_RESULT}" "target_listener_count=0"
assert_result_line "${Q042_FINAL_RESULT}" "vip_announcement_count=0"
assert_result_line "${Q042_FINAL_RESULT}" "sensitive_scan=PASS"
assert_file_sha256 "${Q042_ARCHIVE}" "${EXPECTED_Q042_ARCHIVE_SHA256}"
capture q042-final-result cp "${Q042_FINAL_RESULT}" "${EVIDENCE_DIR}/q042-final-result-copy.env"

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 inodes-before df -hi
capture binaries-before sha256sum "${FORMAL_BINARIES[@]}"
capture unit-files-before sha256sum "${FORMAL_UNIT_FILES[@]}"
assert_units_quiescent "${EVIDENCE_DIR}/units-before.tsv"
assert_runtime_paths_absent "${EVIDENCE_DIR}/runtime-paths-before.tsv"
assert_state_dirs_empty "${EVIDENCE_DIR}/state-dirs-before.tsv"
assert_optional_log_dir_safe_before "${EVIDENCE_DIR}/optional-log-dir-before.tsv"
assert_no_target_listeners "${EVIDENCE_DIR}/listeners-before.txt"
assert_no_vip "${EVIDENCE_DIR}/ipv4-full-before.txt"
assert_space_gate "${EVIDENCE_DIR}/space-before.env"
assert_preseal_host_keys_expected "${EVIDENCE_DIR}/ssh-host-key-files-before.txt"
[[ -s /etc/machine-id ]] || die "machine-id is already empty before seal"
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"

capture seal-dry-run bash "${SEAL_SCRIPT}" --role nginx --bundle-root "${BUNDLE_ROOT}" --dry-run
capture post-clone-dry-run-before env RUN_ID="${RUN_ID}-dry-before" \
  bash "${POST_CLONE_SCRIPT}" --role nginx --node nginx01 \
  --expected-ip "${EXPECTED_IPV4}" --bundle-root "${BUNDLE_ROOT}" --dry-run

if [[ ! -d /var/log/zhct ]]; then
  install -d -m 0750 -o root -g root /var/log/zhct
  CREATED_COMPAT_LOG_DIR=1
fi
printf 'created_compat_log_dir=%s\n' "${CREATED_COMPAT_LOG_DIR}" \
  >"${EVIDENCE_DIR}/compat-log-dir.env"

SEAL_ATTEMPTED=1
capture seal-live env RUN_ID="${RUN_ID}" \
  bash "${SEAL_SCRIPT}" --role nginx --bundle-root "${BUNDLE_ROOT}" --confirm-seal
SEAL_COMPLETED=1
cleanup_compat_dir
if [[ "${CREATED_COMPAT_LOG_DIR}" -eq 1 ]]; then
  [[ ! -e /var/log/zhct && ! -L /var/log/zhct ]] || die "temporary compatibility log directory remains"
fi

assert_units_quiescent "${EVIDENCE_DIR}/units-after.tsv"
assert_runtime_paths_absent "${EVIDENCE_DIR}/runtime-paths-after.tsv"
assert_state_dirs_empty "${EVIDENCE_DIR}/state-dirs-after.tsv"
assert_optional_log_dir_clean "${EVIDENCE_DIR}/optional-log-dir-after.tsv"
assert_no_target_listeners "${EVIDENCE_DIR}/listeners-after.txt"
assert_no_vip "${EVIDENCE_DIR}/ipv4-full-after.txt"
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 inodes-after df -hi
capture binaries-after sha256sum "${FORMAL_BINARIES[@]}"
capture unit-files-after sha256sum "${FORMAL_UNIT_FILES[@]}"
assert_body_unchanged "${EVIDENCE_DIR}/ipv4-before.txt" \
  "${EVIDENCE_DIR}/ipv4-after.txt" "IPv4"
assert_body_unchanged "${EVIDENCE_DIR}/routes-before.txt" \
  "${EVIDENCE_DIR}/routes-after.txt" "routes"
assert_body_unchanged "${EVIDENCE_DIR}/dnf-history-ids-before.txt" \
  "${EVIDENCE_DIR}/dnf-history-ids-after.txt" "DNF history"
assert_body_unchanged "${EVIDENCE_DIR}/binaries-before.txt" \
  "${EVIDENCE_DIR}/binaries-after.txt" "formal binaries"
assert_body_unchanged "${EVIDENCE_DIR}/unit-files-before.txt" \
  "${EVIDENCE_DIR}/unit-files-after.txt" "formal unit files"

capture post-clone-dry-run-after env RUN_ID="${RUN_ID}-dry-after" \
  bash "${POST_CLONE_SCRIPT}" --role nginx --node nginx01 \
  --expected-ip "${EXPECTED_IPV4}" --bundle-root "${BUNDLE_ROOT}" --dry-run

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 file found"
if grep -RInE \
  '(BEGIN[[:space:]]+(RSA|EC|OPENSSH)?[[:space:]]*PRIVATE KEY|AKIA[0-9A-Z]{16}|(password|passwd|token|cookie|secret)[[:space:]]*[:=][[:space:]]*[^_[:space:]]{6,})' \
  "${EVIDENCE_DIR}" --exclude='q043-seal-check.sh' \
  >"${SENSITIVE_SCAN_TMP}"; then
  mv "${SENSITIVE_SCAN_TMP}" "${EVIDENCE_DIR}/sensitive-scan.txt"
  die "sensitive-looking content found in Q043 evidence"
fi
rm -f "${SENSITIVE_SCAN_TMP}"
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 'v1_q042_confirmation_and_evidence=PASS\n'
  printf 'v2_target_identity=PASS\n'
  printf 'v3_framework_integrity=PASS\n'
  printf 'v4_preseal_quiescence=PASS\n'
  printf 'v5_dry_run=PASS\n'
  printf 'v6_live_seal=PASS\n'
  printf 'v7_clone_identity_removed=PASS\n'
  printf 'v8_runtime_state_removed=PASS\n'
  printf 'v9_immutable_state_and_space=PASS\n'
  printf 'v10_post_clone_dry_run_and_evidence=PASS\n'
  printf 'target_units_quiescent=PASS\n'
  printf 'target_listener_count=0\n'
  printf 'vip_announcement_count=0\n'
  printf 'machine_id_bytes=0\n'
  printf 'ssh_host_key_file_count=0\n'
  printf 'sensitive_scan=PASS\n'
  printf 'template_state=SEALED_AWAITING_CUSTOMER_APPLICATION\n'
  printf 'guest_reboot_or_reconnect=FORBIDDEN\n'
  printf 'next_task_execution=LOCKED_PENDING_Q043_USER_CONFIRMATION\n'
  printf 'final_check=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 'q043-final-evidence-index.sha256' \
    -print0 | sort -z | xargs -0 sha256sum >"$(basename "${FINAL_INDEX}")"
)
chmod 0600 "${FINAL_INDEX}"
sha256sum "${FINAL_INDEX}" >"${FINAL_INDEX}.sha256"
chmod 0600 "${FINAL_INDEX}.sha256"
(
  cd "${EVIDENCE_ROOT}"
  tar -czf "${FINAL_ARCHIVE}" "${RUN_ID}"
)
sha256sum "${FINAL_ARCHIVE}" >"${FINAL_ARCHIVE}.sha256"
chmod 0600 "${FINAL_ARCHIVE}" "${FINAL_ARCHIVE}.sha256"

printf 'Q043_TEMPLATE_SEAL_OK\n'
printf 'RUN_ID=%s\n' "${RUN_ID}"
printf 'EVIDENCE_DIR=%s\n' "${EVIDENCE_DIR}"
printf 'FINAL_ARCHIVE=%s\n' "${FINAL_ARCHIVE}"
printf 'FINAL_ARCHIVE_SHA256=%s\n' "$(awk '{print $1}' "${FINAL_ARCHIVE}.sha256")"
printf 'TEMPLATE_STATE=SEALED_AWAITING_CUSTOMER_APPLICATION\n'
printf 'GUEST_REBOOT_OR_RECONNECT=FORBIDDEN\n'
