#!/bin/bash
# 管理会计OS — 环境自检脚本
set -e

echo "===== CMA 环境自检 ====="
echo ""

# 1. 后端服务
echo "[1] 后端服务"
if systemctl is-active cma-backend &>/dev/null; then
  echo "    ✓ cma-backend 运行中"
else
  echo "    ✗ cma-backend 未运行"
fi

# 2. Nginx
echo "[2] Nginx"
if nginx -t 2>&1 | grep -q "successful"; then
  echo "    ✓ Nginx 配置正确"
else
  echo "    ✗ Nginx 配置有误"
fi

# 3. 数据库
echo "[3] 数据库"
if mysql -ucma_user -pcma_pass_2026 -h127.0.0.1 cma -e "SELECT 1;" &>/dev/null; then
  echo "    ✓ MariaDB 连接正常"
else
  echo "    ✗ MariaDB 连接失败"
fi

# 4. API 检查
echo "[4] API 端点"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8010/health 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
  echo "    ✓ API /health 返回 200"
else
  echo "    ✗ API /health 返回 $HTTP_CODE"
fi

# 5. 线上前端
echo "[5] 线上前端"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://cma.sxbh.ltd/ 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
  echo "    ✓ https://cma.sxbh.ltd 返回 200"
else
  echo "    ✗ https://cma.sxbh.ltd 返回 $HTTP_CODE"
fi

# 6. 线上 API
echo "[6] 线上 API"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://cma.sxbh.ltd/api/cma/users 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
  echo "    ✓ /api/cma/users 返回 200"
else
  echo "    ✗ /api/cma/users 返回 $HTTP_CODE"
fi

echo ""
echo "===== 自检完成 ====="
