#!/usr/bin/env bash
# 注册 OCR Worker 为 systemd 服务（后台常驻）
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
PORT="${OCR_PORT:-23567}"

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
  echo "请使用 root 运行: sudo bash install-service.sh"
  exit 1
fi

if [[ ! -d "${ROOT}/.venv" ]]; then
  echo "请先运行: bash ${ROOT}/install.sh"
  exit 1
fi

chmod +x "${ROOT}/start.sh" "${ROOT}/check.sh" "${ROOT}/install.sh"

cat > /etc/systemd/system/ocr-worker.service <<EOF
[Unit]
Description=Grade Archive OCR Worker (PaddleOCR)
After=network.target

[Service]
Type=simple
WorkingDirectory=${ROOT}
Environment=OCR_USE_GPU=true
Environment=OCR_PORT=${PORT}
Environment=OCR_HOST=0.0.0.0
ExecStart=${ROOT}/.venv/bin/uvicorn app:app --host 0.0.0.0 --port ${PORT} --log-level info
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable ocr-worker
systemctl restart ocr-worker

sleep 2
echo ""
echo "==> 服务状态:"
systemctl status ocr-worker --no-pager -l | head -20

echo ""
echo "==> 健康检查:"
curl -sS "http://127.0.0.1:${PORT}/health" || echo "（尚未就绪，请稍等 30 秒后重试: bash check.sh）"
echo ""
echo "局域网地址: http://$(hostname -I 2>/dev/null | awk '{print $1}'):${PORT}"
echo "成绩档案系统设置 OCR 地址填: http://192.168.8.6:${PORT}  （按实际 IP 修改）"
