#!/bin/bash
# 云盘后端服务安装脚本

set -e

# 配置变量
SERVICE_NAME="cloud-drive"
SERVICE_USER="cloud-drive"
INSTALL_DIR="/opt/cloud-drive"
SERVICE_FILE="cloud-drive.service"

echo "=== 云盘后端服务安装脚本 ==="

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "错误: 请使用root权限运行此脚本"
    exit 1
fi

# 检查系统
if [ -f /etc/os-release ]; then
    . /etc/os-release
    echo "检测到系统: $NAME $VERSION"
else
    echo "警告: 无法检测系统版本"
fi

# 创建服务用户
echo "创建服务用户..."
if ! id "$SERVICE_USER" &>/dev/null; then
    useradd -r -s /bin/false -d "$INSTALL_DIR" "$SERVICE_USER"
    echo "✓ 创建用户 $SERVICE_USER"
else
    echo "✓ 用户 $SERVICE_USER 已存在"
fi

# 创建安装目录
echo "创建安装目录..."
mkdir -p "$INSTALL_DIR"
mkdir -p "$INSTALL_DIR/logs"
mkdir -p "$INSTALL_DIR/uploads"

# 复制文件
echo "复制服务文件..."
if [ -f "deploy/cloud-drive-server" ]; then
    cp deploy/cloud-drive-server "$INSTALL_DIR/"
    chmod +x "$INSTALL_DIR/cloud-drive-server"
    echo "✓ 复制可执行文件"
else
    echo "错误: 未找到可执行文件，请先运行打包脚本"
    exit 1
fi

if [ -f "deploy/.env.example" ]; then
    cp deploy/.env.example "$INSTALL_DIR/.env.example"
    echo "✓ 复制配置文件模板"
fi

# 设置权限
echo "设置文件权限..."
chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"
chmod 755 "$INSTALL_DIR"
chmod 755 "$INSTALL_DIR/cloud-drive-server"
chmod 755 "$INSTALL_DIR/logs"
chmod 755 "$INSTALL_DIR/uploads"

# 安装systemd服务
echo "安装systemd服务..."
cp "$SERVICE_FILE" "/etc/systemd/system/"
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
echo "✓ 服务已安装并启用"

# 配置防火墙（如果存在）
echo "配置防火墙..."
if command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-port=8000/tcp
    firewall-cmd --reload
    echo "✓ 防火墙配置完成 (firewalld)"
elif command -v ufw &> /dev/null; then
    ufw allow 8000/tcp
    echo "✓ 防火墙配置完成 (ufw)"
else
    echo "注意: 未检测到防火墙管理工具，请手动开放8000端口"
fi

# 创建日志轮转配置
echo "配置日志轮转..."
cat > /etc/logrotate.d/cloud-drive << EOF
$INSTALL_DIR/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 $SERVICE_USER $SERVICE_USER
    postrotate
        systemctl reload cloud-drive || true
    endscript
}
EOF
echo "✓ 日志轮转配置完成"

# 提示配置
echo ""
echo "=== 安装完成 ==="
echo "安装目录: $INSTALL_DIR"
echo ""
echo "下一步操作:"
echo "1. 编辑配置文件: nano $INSTALL_DIR/.env"
echo "2. 启动服务: systemctl start $SERVICE_NAME"
echo "3. 查看状态: systemctl status $SERVICE_NAME"
echo "4. 查看日志: journalctl -u $SERVICE_NAME -f"
echo ""
echo "服务将在以下地址提供API:"
echo "- API文档: http://$(hostname -I | awk '{print $1}'):8000/docs"
echo "- 健康检查: http://$(hostname -I | awk '{print $1}'):8000/api/v1/health"