#!/usr/bin/env bash
#
# 卸载中学成绩档案系统（停止服务 + 可选删除数据/目录）
# 用法:
#   sudo bash deploy/uninstall.sh              # 停止服务，保留代码/数据库/上传
#   sudo bash deploy/uninstall.sh --purge        # 额外删除 /opt/secondary-school-grade-archive
#   sudo bash deploy/uninstall.sh --purge-db     # 额外删除 PostgreSQL 库与用户
#   sudo bash deploy/uninstall.sh --purge --purge-db  # 完全清除后重装
#
set -euo pipefail

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

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

PURGE_DIR=0
PURGE_DB=0
for arg in "$@"; do
  case "${arg}" in
    --purge) PURGE_DIR=1 ;;
    --purge-db) PURGE_DB=1 ;;
    -h|--help)
      sed -n '2,8p' "$0"
      exit 0
      ;;
  esac
done

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
  log_error "请使用 root: sudo bash deploy/uninstall.sh"
  exit 1
fi

if [[ -f "${INSTALL_DIR}/.env" ]]; then
  # shellcheck disable=SC1090
  set -a && source "${INSTALL_DIR}/.env" && set +a
fi

POSTGRES_USER="${POSTGRES_USER:-gradeapp}"
POSTGRES_DB="${POSTGRES_DB:-student_archive}"

echo ""
echo "=========================================="
echo "  卸载中学成绩档案系统"
echo "=========================================="
echo "  安装目录: ${INSTALL_DIR}"
echo "  删除目录: $([[ ${PURGE_DIR} -eq 1 ]] && echo 是 || echo 否（保留）)"
echo "  删除数据库: $([[ ${PURGE_DB} -eq 1 ]] && echo 是 || echo 否（保留）)"
echo "=========================================="
echo ""

if [[ -t 0 ]]; then
  read -rp "确认继续? [y/N] " confirm
  if [[ "${confirm}" != [yY] ]]; then
    echo "已取消"
    exit 0
  fi
fi

log_info "停止主程序 systemd…"
systemctl stop grade-archive 2>/dev/null || true
systemctl disable grade-archive 2>/dev/null || true
rm -f /etc/systemd/system/grade-archive.service
systemctl daemon-reload

log_info "停止 OCR Worker systemd（若曾安装）…"
systemctl stop ocr-worker 2>/dev/null || true
systemctl disable ocr-worker 2>/dev/null || true
rm -f /etc/systemd/system/ocr-worker.service
systemctl daemon-reload

log_info "停止 OCR screen 会话…"
if command -v screen >/dev/null; then
  screen -S "${OCR_SCREEN_NAME}" -X quit 2>/dev/null || true
fi

log_info "停止旧版 PM2（若存在）…"
if command -v pm2 >/dev/null; then
  pm2 delete grade-api grade-web 2>/dev/null || true
  pm2 save --force 2>/dev/null || true
fi

if [[ ${PURGE_DB} -eq 1 ]]; then
  if command -v psql >/dev/null && systemctl is-active postgresql &>/dev/null; then
    log_info "删除 PostgreSQL 数据库 ${POSTGRES_DB}…"
    sudo -u postgres psql -c "DROP DATABASE IF EXISTS \"${POSTGRES_DB}\";" 2>/dev/null || true
    sudo -u postgres psql -c "DROP USER IF EXISTS \"${POSTGRES_USER}\";" 2>/dev/null || true
  else
    log_warn "PostgreSQL 未运行，跳过删库"
  fi
fi

if [[ ${PURGE_DIR} -eq 1 ]]; then
  log_info "删除安装目录 ${INSTALL_DIR}…"
  rm -rf "${INSTALL_DIR}"
else
  log_info "保留安装目录（含 uploads、.env、数据库文件若未 --purge-db）"
fi

echo ""
echo "=========================================="
echo "  卸载完成"
echo "=========================================="
if [[ ${PURGE_DIR} -eq 0 ]]; then
  echo "  代码仍在: ${INSTALL_DIR}"
  echo "  重新部署:"
  echo "    cd ${INSTALL_DIR} && git pull"
  echo "    export OLLAMA_BASE_URL=http://Ollama电脑IP:11434"
  echo "    sudo bash deploy/install.sh"
else
  echo "  重新部署（全新）:"
  echo "    export OLLAMA_BASE_URL=http://Ollama电脑IP:11434"
  echo "    sudo bash deploy/install.sh"
  echo "  （install.sh 会自动 git clone 到 ${INSTALL_DIR}）"
fi
echo "=========================================="
