#!/usr/bin/env bash
set -euo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/secondary-school-grade-archive}"
BRANCH="${BRANCH:-main}"
PIP_MIRROR="${PIP_MIRROR:-https://pypi.tuna.tsinghua.edu.cn/simple}"

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

require_root "deploy/update.sh"

cd "${INSTALL_DIR}" || exit 1
find "${INSTALL_DIR}" -name "*.sh" -exec sed -i 's/\r$//' {} +
chmod +x deploy/start.sh deploy/ocr-screen.sh deploy/install-ocr-deps.sh deploy/repair.sh
chmod +x deploy/ocr-worker/*.sh 2>/dev/null || true

setup_deploy_proxy

log_info "拉取最新代码…"
git fetch origin
git checkout "${BRANCH}" 2>/dev/null || true
git pull origin "${BRANCH}"

if [[ ! -f "${INSTALL_DIR}/frontend/dist/index.html" ]]; then
  log_error "未找到 frontend/dist/index.html"
  exit 1
fi

log_info "更新主程序依赖…"
cd backend
source venv/bin/activate
pip install -r requirements.txt --progress-bar on -i "${PIP_MIRROR}"
deactivate
cd "${INSTALL_DIR}"

log_info "更新 OCR Worker 并重启 screen…"
install_ocr_worker
stop_ocr_screen
start_ocr_screen
wait_ocr_healthy || log_warn "OCR 加载中，稍后: bash deploy/ocr-screen.sh status"

stop_legacy_pm2
install_ocr_deps_safe
setup_systemd_service
restart_grade_service

if ! wait_healthy; then
  log_error "更新后主程序异常，可尝试: sudo bash ${INSTALL_DIR}/deploy/repair.sh"
  exit 1
fi

log_info "更新完成"
show_ocr_status
