#!/usr/bin/env bash

set -Eeuo pipefail

bundle_root='/opt/zhct-deploy'
backup_root='/var/backups/zhct-q101/files/q101-20260727T112000-bundle-refresh'

echo Q101_PARTIAL_REFRESH_ASSESS_BEGIN
date -Is
[[ "$(hostname -s)" == 'sqjcnginx01' ]]
hostname -s
ip -o -4 addr show
ip -o -4 addr show scope global | grep -F '10.2.203.102/'

sha256sum \
  "$bundle_root/roles/nginx/templates/nginx/nginx.conf" \
  "$bundle_root/roles/nginx/hooks.sh" \
  "$bundle_root/roles/nginx/templates/systemd/nginx.service" \
  "$bundle_root/validate-assets.sh" \
  /etc/systemd/system/nginx.service \
  /usr/local/nginx/conf/nginx.conf

grep -E \
  'roles/nginx/hooks.sh|roles/nginx/templates/nginx/nginx.conf|roles/nginx/templates/systemd/nginx.service|validate-assets.sh' \
  "$bundle_root/manifests/bundle.sha256"

find "$backup_root" \
  -type f -printf 'BACKUP=%p MODE=%m OWNER=%u:%g SIZE=%s\n' |
  sort

sha256sum \
  "$backup_root/opt/zhct-deploy/roles/nginx/templates/nginx/nginx.conf" \
  "$backup_root/opt/zhct-deploy/roles/nginx/hooks.sh" \
  "$backup_root/opt/zhct-deploy/roles/nginx/templates/systemd/nginx.service" \
  "$backup_root/opt/zhct-deploy/manifests/bundle.sha256" \
  "$backup_root/etc/systemd/system/nginx.service"

for marker in .source-commit .framework-bundle-sha256; do
  if [[ -f "$bundle_root/$marker" ]]; then
    stat -c 'MARKER=%n MODE=%a OWNER=%U:%G SIZE=%s' "$bundle_root/$marker"
    sha256sum "$bundle_root/$marker"
  else
    echo "MARKER_ABSENT=$marker"
  fi
done

find "$bundle_root" -mindepth 1 -maxdepth 2 \
  -printf 'ENTRY=%y %p\n' |
  sort

systemctl show nginx.service \
  -p MainPID -p ActiveEnterTimestamp \
  -p LimitNOFILE -p LimitNOFILESoft
nginx_pid=$(systemctl show nginx.service -p MainPID --value)
[[ "$nginx_pid" =~ ^[1-9][0-9]*$ ]]
grep 'Max open files' "/proc/$nginx_pid/limits"

for unit in nginx haproxy orchestrator; do
  systemctl is-enabled --quiet "$unit"
  systemctl is-active --quiet "$unit"
done
for unit in sentinel5 sentinel7 keepalived; do
  [[ "$(systemctl is-enabled "$unit" 2>/dev/null || true)" == 'disabled' ]]
  [[ "$(systemctl is-active "$unit" 2>/dev/null || true)" == 'inactive' ]]
done

for unit in nginx haproxy orchestrator sentinel5 sentinel7 keepalived; do
  echo "UNIT=$unit ENABLED=$(systemctl is-enabled "$unit" 2>/dev/null || true)"
  echo "UNIT=$unit ACTIVE=$(systemctl is-active "$unit" 2>/dev/null || true)"
done

if ip -o -4 addr show | grep -Eq '10\.2\.203\.(115|116|117)/'; then
  echo Q101_UNEXPECTED_VIP_PRESENT
  exit 1
fi

echo Q101_VIP_ABSENT=PASS
echo Q101_PARTIAL_REFRESH_ASSESS_PASS
