#!/bin/bash
set -euo pipefail
[[ $(id -u) == 0 ]] || { echo '请使用root'; exit 1; }
[[ $(uname -m) == x86_64 && $(getconf GNU_LIBC_VERSION) == 'glibc 2.28' ]] || { echo '运行架构或glibc不匹配'; exit 1; }
ROOT=$(cd -- "$(dirname -- "$0")" && pwd -P)
DEST=/opt/zhct-redis627
DATA=/data/redis/zhct
UNIT=/etc/systemd/system/zhct-redis627.service
python3 - <<'PYGUARD'
from pathlib import Path
for raw in ('/opt','/data','/data/redis','/etc/systemd/system','/var/lib'):
 p=Path(raw)
 for item in (p,)+tuple(p.parents):
  if item.is_symlink():raise SystemExit('Symlink parent rejected: '+str(item))
  if item.exists() and not item.is_dir():raise SystemExit('Not a directory: '+str(item))
print('安装父路径检查通过')
PYGUARD
for P in "$DEST" "$DATA" "$UNIT" /var/lib/zhct-redis627; do
 [[ ! -e "$P" && ! -L "$P" ]] || { echo "已有目标，停止，不覆盖：$P"; exit 1; }
done
if systemctl cat zhct-redis627.service >/dev/null 2>&1; then echo '已有同名服务，停止'; exit 1; fi
if getent passwd zhctredis >/dev/null || getent group zhctredis >/dev/null; then echo '已有同名账号/组，停止核对'; exit 1; fi
python3 - <<'PYCODE'
import socket
s=socket.socket();s.bind(('127.0.0.1',6379));s.close();print('6379端口可用')
PYCODE
cd "$ROOT"
sha256sum -c PAYLOAD.sha256 > payload-check.log 2>&1 || { tail -n 20 payload-check.log; exit 1; }
python3 scripts/check-install.py "$ROOT"
useradd --system --user-group --home-dir /var/lib/zhct-redis627 --create-home --shell /sbin/nologin zhctredis
install -d -m 755 "$DEST"
cp -a bin etc scripts licenses RUNTIME.json "$DEST/"
chown -R root:root "$DEST"
chown root:zhctredis "$DEST/etc/redis.conf"
chmod 640 "$DEST/etc/redis.conf"
install -d -o zhctredis -g zhctredis -m 750 "$DATA"
runuser -u zhctredis -- python3 "$DEST/scripts/check-install.py" "$DEST"
install -m 644 "$DEST/etc/zhct-redis627.service" "$UNIT"
systemctl daemon-reload
echo 'Redis6.2.7安装与检查完成；未启动，未设置开机启动。'
echo '版本与旧前厅实际运行实例一致；未复制旧RDB/AOF，业务启用前须检查旧队列与状态。'
