#!/bin/bash

set -euo pipefail

KVER="${KVER:-5.10.134-19.8.al8.aarch64}"
EVIDENCE_DIR="${EVIDENCE_DIR:-/root/kernel-remediation-postcheck-$(date +%Y%m%d%H%M%S)}"

if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: run as root" >&2
    exit 1
fi

mkdir -p "$EVIDENCE_DIR"
exec > >(tee -a "$EVIDENCE_DIR/postcheck.txt") 2>&1

echo "BEGIN=$(date --iso-8601=seconds)"
echo "HOST=$(hostname)"
echo "EXPECTED_KERNEL=$KVER"
echo "RUNNING_KERNEL=$(uname -r)"

if [ "$(uname -r)" != "$KVER" ]; then
    echo "ERROR: server is not running the expected kernel" >&2
    exit 1
fi

ip -4 -o addr show scope global
uptime
df -h / /boot 2>&1 || true
rpm -qa 'kernel*' | sort
grubby --default-kernel
systemctl --failed --no-pager
systemctl list-units --type=service --state=running --no-pager
ss -lntp

journalctl -b -p err --no-pager > "$EVIDENCE_DIR/journal-errors.txt" 2>&1 || true
dmesg --level=err,crit,alert,emerg > "$EVIDENCE_DIR/dmesg-errors.txt" 2>&1 || true

cat > "$EVIDENCE_DIR/role-acceptance.txt" <<'EOF'
Complete the matching role checks manually and attach the output:
- Nginx: HTTPS certificate, reverse proxy, static assets, external request.
- Application: Nginx, PHP-FPM, Supervisor, log write, core APIs.
- OceanBase: primary/standby state, observer, OBProxy, replication, ports 2881-2886.
- Redis: service, authentication, persistence, application connection, port 6379.
- Baidu face: HTTP /health, authorization and expected face count, port 18080.
- EMQX: ports 1883/18083, clients, subscriptions and publish/receive test.
EOF

echo "POSTCHECK_BASE_OK=1"
echo "ROLE_ACCEPTANCE_REQUIRED=1"
echo "SCANNER_RESCAN_REQUIRED=1"
echo "EVIDENCE_DIR=$EVIDENCE_DIR"

