#!/usr/bin/env bash
#
# 服务无法访问（连接被拒绝）时一键修复
# 用法: sudo bash deploy/repair.sh
#
set -euo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/secondary-school-grade-archive}"

# shellcheck source=common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh"
# shellcheck source=ocr-common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ocr-common.sh"

require_root "deploy/repair.sh"

cd "${INSTALL_DIR}" || exit 1
find "${INSTALL_DIR}" -name "*.sh" -exec sed -i 's/\r$//' {} +

log_info "开始修复 grade-archive 服务…"

stop_legacy_pm2
install_ocr_deps_safe
if [[ -x "${INSTALL_DIR}/deploy/ocr-worker/.venv/bin/uvicorn" ]]; then
  start_ocr_screen || log_warn "OCR screen 启动失败"
  wait_ocr_healthy || log_warn "OCR 未就绪"
fi
setup_systemd_service
restart_grade_service

if wait_healthy; then
  ip=$(hostname -I 2>/dev/null | awk '{print $1}')
  ip="${ip:-127.0.0.1}"
  echo ""
  echo "=========================================="
  echo "  修复完成，请访问: http://${ip}:${WEB_PORT}"
  echo "=========================================="
else
  show_service_status
  exit 1
fi
