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

RUN_ID=${1:-$(date '+%Y%m%dT%H%M%S%z')}
PACKAGE_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)
SOURCE_HOOK="$PACKAGE_ROOT/deployment-assets/roles/mysql/hooks.sh"
TARGET_HOOK=/opt/zhct-deploy/roles/mysql/hooks.sh
OLD_HOOK_SHA=bc84b31dee8640f01b328b863fdc991311571649c68654b7c2c5183268f1619a
NEW_HOOK_SHA=56d68209ab3dc5da3f4ab2c0b679329fc27892749de5b4f65ff9b72e1ccfd8fd
EVIDENCE_DIR="/var/backups/zhct-q063/$RUN_ID"
ARCHIVE="/root/sanquan-mysql01-q063-evidence-$RUN_ID.tar.gz"
BUNDLE=/opt/zhct-deploy

die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
[[ $(id -u) -eq 0 ]] || die "root required"
[[ "$RUN_ID" =~ ^[0-9]{8}T[0-9]{6}[+-][0-9]{4}$ ]] || die "invalid run id"
[[ "$(hostname -s | tr '[:upper:]' '[:lower:]')" == sqjcdb01 ]] || die "wrong host"
[[ ! -e "$EVIDENCE_DIR" && ! -e "$ARCHIVE" ]] || die "run evidence already exists"
install -d -m 0700 "$EVIDENCE_DIR"

grep -Fxq 'final_closeout=PASS' /var/backups/zhct-q062/20260727T160030+0800/final-closeout.env ||
  die "Q062 final evidence missing"
[[ $(sha256sum "$SOURCE_HOOK" | awk '{print $1}') == "$NEW_HOOK_SHA" ]] ||
  die "source hook mismatch"
[[ $(sha256sum "$TARGET_HOOK" | awk '{print $1}') == "$OLD_HOOK_SHA" ]] ||
  die "unexpected remote hook"
cp -a "$TARGET_HOOK" "$EVIDENCE_DIR/hooks-before.sh"
install -m 0750 -o root -g root "$SOURCE_HOOK" "$TARGET_HOOK"
bash -n "$TARGET_HOOK"
sha256sum "$TARGET_HOOK" >"$EVIDENCE_DIR/hooks-after.sha256"

for unit in mysql56.service mysql80.service mysql-health56.service mysql-health80.service; do
  [[ $(systemctl is-enabled "$unit" 2>/dev/null || true) == disabled ]] || die "unit enabled: $unit"
  ! systemctl is-active --quiet "$unit" || die "unit active: $unit"
done
! pgrep -x mysqld >/dev/null || die "mysqld running"
ss -lntup >"$EVIDENCE_DIR/listeners-before.txt"
! grep -Eq ':(3306|3308|9201|9202|33060)([[:space:]]|$)' "$EVIDENCE_DIR/listeners-before.txt" ||
  die "target listener exists"
for path in /data/mysql56 /data/mysql80; do
  ! find "$path" -mindepth 1 ! -type d -print -quit | grep -q . || die "formal data exists"
done
rpm -qa | sort >"$EVIDENCE_DIR/rpm-before.txt"
dnf history list --reverse >"$EVIDENCE_DIR/dnf-history-before.txt"
sha256sum /opt/mysql/5.6.51/bin/mysqld /opt/mysql/8.0.46/bin/mysqld \
  /opt/mysql/8.0.46/lib/plugin/component_reference_cache.so >"$EVIDENCE_DIR/runtime-before.sha256"

command -v unshare >/dev/null || die "unshare missing"
unshare --net bash -Eeuo pipefail -c '
  [[ -z "$(ip route show)" ]] || { echo "ERROR: isolated namespace has route"; exit 1; }
  printf "network_namespace_routes=NONE\n"
  RUN_ID="$1" BUNDLE_ROOT=/opt/zhct-deploy \
    bash /opt/zhct-deploy/common/scripts/install-role.sh --role mysql --bundle-root /opt/zhct-deploy
  RUN_ID="$1" BUNDLE_ROOT=/opt/zhct-deploy \
    bash /opt/zhct-deploy/common/scripts/verify-role.sh --role mysql --bundle-root /opt/zhct-deploy
' _ "$RUN_ID" >"$EVIDENCE_DIR/offline-verify.stdout" 2>"$EVIDENCE_DIR/offline-verify.stderr"

rpm -qa | sort >"$EVIDENCE_DIR/rpm-after.txt"
cmp -s "$EVIDENCE_DIR/rpm-before.txt" "$EVIDENCE_DIR/rpm-after.txt" ||
  die "RPM set changed"
dnf history list --reverse >"$EVIDENCE_DIR/dnf-history-after.txt"
cmp -s "$EVIDENCE_DIR/dnf-history-before.txt" "$EVIDENCE_DIR/dnf-history-after.txt" ||
  die "DNF history changed"
sha256sum /opt/mysql/5.6.51/bin/mysqld /opt/mysql/8.0.46/bin/mysqld \
  /opt/mysql/8.0.46/lib/plugin/component_reference_cache.so >"$EVIDENCE_DIR/runtime-after.sha256"
cmp -s "$EVIDENCE_DIR/runtime-before.sha256" "$EVIDENCE_DIR/runtime-after.sha256" ||
  die "runtime binary changed"
grep -Fxq 'network_namespace_routes=NONE' "$EVIDENCE_DIR/offline-verify.stdout"
grep -Fq 'install completed for role=mysql' "$EVIDENCE_DIR/offline-verify.stderr"
grep -Fq 'verify completed for role=mysql' "$EVIDENCE_DIR/offline-verify.stderr"

pgrep -a -x mysqld >"$EVIDENCE_DIR/final-mysqld-processes.txt" 2>&1 || true
[[ ! -s "$EVIDENCE_DIR/final-mysqld-processes.txt" ]] || die "mysqld remains"
ss -lntup >"$EVIDENCE_DIR/final-listeners.txt"
! grep -Eq ':(3306|3308|9201|9202|33060)([[:space:]]|$)' "$EVIDENCE_DIR/final-listeners.txt" ||
  die "target listener remains"
: >"$EVIDENCE_DIR/final-units.txt"
for unit in mysql56.service mysql80.service mysql-health56.service mysql-health80.service; do
  enabled=$(systemctl is-enabled "$unit" 2>/dev/null || true)
  active=$(systemctl is-active "$unit" 2>/dev/null || true)
  printf '%s enabled=%s active=%s\n' "$unit" "$enabled" "$active" >>"$EVIDENCE_DIR/final-units.txt"
  [[ "$enabled" == disabled && "$active" == inactive ]] || die "unit state changed: $unit"
done

cat >"$EVIDENCE_DIR/result.env" <<EOF
run_id=$RUN_ID
hook_update=PASS
network_namespace=NO_ROUTES
offline_install_idempotence=PASS
offline_role_verify=PASS
rpm_set_unchanged=PASS
dnf_history_unchanged=PASS
runtime_sha256_unchanged=PASS
formal_data_initialized=NOT_PERFORMED
post_clone_execution=NOT_PERFORMED
service_activation=NOT_PERFORMED
EOF
tar --create --gzip --file="$ARCHIVE" --directory=/ "var/backups/zhct-q063/$RUN_ID"
chmod 0600 "$ARCHIVE"
cat "$EVIDENCE_DIR/result.env" "$EVIDENCE_DIR/final-units.txt"
sha256sum "$ARCHIVE"
stat -c 'bytes=%s' "$ARCHIVE"
printf 'Q063_OFFLINE_CACHE_ONLY_VERIFY_AND_ARCHIVE_OK\n'
