#!/bin/bash
# ============================================================
# 问题排查助手 - Linux 部署脚本
# 运行方式: bash deploy.sh
# ============================================================

set -e

echo "=================================================="
echo "  问题排查助手 部署脚本"
echo "=================================================="

# 配置
DEPLOY_DIR="/opt/troubleshoot"
WEB_PORT=8088
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "[1/4] 安装 Python 依赖..."
pip3 install flask openpyxl -q 2>/dev/null || pip install flask openpyxl -q

echo "[2/4] 创建部署目录..."
sudo mkdir -p $DEPLOY_DIR
sudo cp -r "$SCRIPT_DIR/web" "$DEPLOY_DIR/"
sudo cp -r "$SCRIPT_DIR/问题记录" "$DEPLOY_DIR/"
sudo cp "$SCRIPT_DIR/搜索索引.json" "$DEPLOY_DIR/"
sudo cp "$SCRIPT_DIR/build_index.py" "$DEPLOY_DIR/"

echo "[3/4] 配置权限..."
sudo chown -R $USER:$USER $DEPLOY_DIR

echo "[4/4] 创建 systemd 服务..."
sudo tee /etc/systemd/system/troubleshoot.service > /dev/null << EOF
[Unit]
Description=问题排查助手 Web 服务
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$DEPLOY_DIR/web
ExecStart=/usr/bin/python3 $DEPLOY_DIR/web/server.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable troubleshoot.service
sudo systemctl start troubleshoot.service

echo ""
echo "=================================================="
echo "  部署完成！"
echo "=================================================="
echo "  访问地址: http://192.168.5.60:$WEB_PORT"
echo "  查看状态: sudo systemctl status troubleshoot"
echo "  查看日志: sudo journalctl -u troubleshoot -f"
echo "  重启服务: sudo systemctl restart troubleshoot"
echo "=================================================="