#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

LABEL=REDIS01_Q131_EXECUTE_READINESS
EXPECTED_HOST=sqjcredis01
EXPECTED_IP=10.2.203.112
PACKAGE_SHA=6cbf051f83d6b989bb88d33cc47d1b4e4027653809e5bbf9ae6402b3762d9651
ARCHIVE=/root/redis-q131-q132-delivery.tar.gz
PACKAGE_DIR=/root/redis-q131-q132-delivery
Q073_RESULT=/var/backups/zhct-q073/q073-20260727T181115+0800/result.env
RUN_ID="q131-execute-readiness-$(date +%Y%m%dT%H%M%S%z)"
AUDIT_DIR="/var/backups/zhct-manual-preflight/${RUN_ID}"
AUDIT_LOG="${AUDIT_DIR}/operator.log"

finish() {
    rc=$?
    trap - EXIT
    printf 'END|%s|RC=%s|AUDIT_LOG=%s\n' \
        "$LABEL" "$rc" "${AUDIT_LOG:-NOT_CREATED}"
    exit "$rc"
}
trap finish EXIT

printf 'BEGIN|%s|%s\n' "$LABEL" "$(date --iso-8601=seconds)"
actual_host=$(hostname -s)
printf 'IDENTITY|hostname=%s|expected=%s\n' "$actual_host" "$EXPECTED_HOST"
test "$actual_host" = "$EXPECTED_HOST"
ip -o -4 addr show scope global |
    awk '{split($4,a,"/"); print a[1]}' |
    grep -Fxq "$EXPECTED_IP"
if ip -o -4 addr show scope global |
    awk '{split($4,a,"/"); print a[1]}' |
    grep -Eq '^10\.2\.203\.(115|116|117)$'
then
    echo 'ERROR: VIP is present'
    exit 1
fi

install -d -o root -g root -m 0700 "$AUDIT_DIR"
exec > >(tee -a "$AUDIT_LOG") 2>&1
printf 'AUDIT_BEGIN|%s|%s\n' "$LABEL" "$(date --iso-8601=seconds)"

printf '%s\n' '=== Q073 RECEIPT ==='
test -r "$Q073_RESULT"
grep -Fxq 'q073=PASS' "$Q073_RESULT"
grep -Fxq 'clone_identity_removed=PASS' "$Q073_RESULT"
grep -Fxq 'machine_id_bytes=0' "$Q073_RESULT"
grep -Fxq 'ssh_host_key_file_count=0' "$Q073_RESULT"
grep -Fxq 'post_clone_execution=NOT_PERFORMED' "$Q073_RESULT"
grep -E \
    '^(run_id|completed_at|q073|clone_identity_removed|machine_id_bytes|ssh_host_key_file_count|post_clone_execution|template_state)=' \
    "$Q073_RESULT"

printf '%s\n' '=== CURRENT PARTIAL IDENTITY ==='
test ! -s /etc/machine-id
test ! -e /var/lib/dbus/machine-id
test ! -e /etc/zhct/node.env
private_key_count=$(find /etc/ssh -maxdepth 1 -type f -name 'ssh_host_*_key' |
    awk 'END {print NR+0}')
all_key_count=$(find /etc/ssh -maxdepth 1 -type f -name 'ssh_host_*' |
    awk 'END {print NR+0}')
test "$private_key_count" -eq 3
test "$all_key_count" -eq 6
printf 'CURRENT_IDENTITY|machine=0|private_keys=%s|all_key_files=%s|env=0\n' \
    "$private_key_count" "$all_key_count"
q073_epoch=$(date -d '2026-07-27 18:11:20 +0800' +%s)
while IFS= read -r -d '' file; do
    birth_epoch=$(stat -c %W "$file")
    test "$birth_epoch" -gt "$q073_epoch"
    stat -c 'POST_SEAL_KEY|%w|%s|%A|%U:%G|%n' "$file"
done < <(find /etc/ssh -maxdepth 1 -type f -name 'ssh_host_*' -print0 | sort -z)

printf '%s\n' '=== PACKAGE ==='
test -f "$ARCHIVE"
printf '%s  %s\n' "$PACKAGE_SHA" "$ARCHIVE" | sha256sum -c -
test -d "$PACKAGE_DIR"
(cd "$PACKAGE_DIR" && sha256sum -c SHA256SUMS)
test -x "$PACKAGE_DIR/redis-q131-q132"
bash -n "$PACKAGE_DIR/redis-q131-q132"

printf '%s\n' '=== SECRET METADATA ONLY ==='
for file in \
    /etc/zhct/secrets/redis5.password \
    /etc/zhct/secrets/redis7.password
do
    test -s "$file"
    test "$(stat -c %U:%G "$file")" = root:root
    case "$(stat -c %a "$file")" in
        400|600) ;;
        *) echo "ERROR: invalid secret mode: $file"; exit 1 ;;
    esac
    test "$(awk 'END {print NR+0}' "$file")" -eq 1
    stat -c 'SECRET_METADATA|PRESENT_NONEMPTY|%A|%U:%G|%s|%n' "$file"
done

printf '%s\n' '=== UNIT POLICY ==='
for unit in redis5 redis7 sentinel5 sentinel7 orchestrator; do
    enabled_state=$(systemctl is-enabled "$unit.service" 2>/dev/null || true)
    active_state=$(systemctl is-active "$unit.service" 2>/dev/null || true)
    printf 'UNIT|%s.service|enabled=%s|active=%s\n' \
        "$unit" "$enabled_state" "$active_state"
    test "$enabled_state" = disabled
    test "$active_state" = inactive
done

printf '%s\n' '=== PROCESSES AND LISTENERS ==='
if pgrep -af '(^|/)(redis-server|redis-sentinel|orchestrator)([[:space:]]|$)'
then
    echo 'ERROR: role process exists'
    exit 1
else
    echo 'ROLE_PROCESSES=NONE'
fi
if ss -lntupH |
    grep -E ':(6379|6387|26379|26387|3000|10008)([[:space:]]|$)'
then
    echo 'ERROR: target listener exists'
    exit 1
else
    echo 'TARGET_LISTENERS=NONE'
fi

printf '%s\n' '=== CAPACITY ==='
df -hT /
free -h
echo 'Q131_EXECUTE_READINESS=PASS_NO_MUTATION'
echo 'NEXT_ACTION=BOUNDED_BACKUP_POST_SEAL_KEYS_AND_Q131_EXECUTE'
