#!/bin/bash
# 云盘后端服务卸载脚本

set -e

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

echo "=== 云盘后端服务卸载脚本 ==="

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

# 停止并禁用服务
echo "停止服务..."
if systemctl is-active --quiet "$SERVICE_NAME"; then
    systemctl stop "$SERVICE_NAME"
    echo "✓ 服务已停止"
fi

echo "禁用服务..."
if systemctl is-enabled --quiet "$SERVICE_NAME"; then
    systemctl disable "$SERVICE_NAME"
    echo "✓ 服务已禁用"
fi

# 删除systemd服务文件
echo "删除systemd服务..."
if [ -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
    rm -f "/etc/systemd/system/$SERVICE_NAME.service"
    systemctl daemon-reload
    echo "✓ systemd服务文件已删除"
fi

# 删除防火墙规则
echo "删除防火墙规则..."
if command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --remove-port=8000/tcp 2>/dev/null || true
    firewall-cmd --reload 2>/dev/null || true
    echo "✓ 防火墙规则已删除 (firewalld)"
elif command -v ufw &> /dev/null; then
    ufw delete allow 8000/tcp 2>/dev/null || true
    echo "✓ 防火墙规则已删除 (ufw)"
fi

# 删除日志轮转配置
echo "删除日志轮转配置..."
if [ -f "/etc/logrotate.d/cloud-drive" ]; then
    rm -f "/etc/logrotate.d/cloud-drive"
    echo "✓ 日志轮转配置已删除"
fi

# 询问是否删除数据
echo ""
read -p "是否删除所有数据和配置文件？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    # 删除安装目录
    echo "删除安装目录..."
    if [ -d "$INSTALL_DIR" ]; then
        rm -rf "$INSTALL_DIR"
        echo "✓ 安装目录已删除"
    fi

    # 删除服务用户
    echo "删除服务用户..."
    if id "$SERVICE_USER" &>/dev/null; then
        userdel "$SERVICE_USER" 2>/dev/null || true
        echo "✓ 服务用户已删除"
    fi

    echo "✓ 所有数据已删除"
else
    echo "保留数据目录: $INSTALL_DIR"
    echo "如需手动删除，请运行: rm -rf $INSTALL_DIR"
fi

echo ""
echo "=== 卸载完成 ==="
echo "云盘后端服务已从系统中完全移除"