#!/bin/bash
set -e

INSTALL_DIR="/opt/lan-manager"
SERVICE_NAME="lan-manager"
USER_NAME="lanmgr"

echo "=== LAN Manager 卸载脚本 ==="

if [ "$EUID" -ne 0 ]; then
  echo "请使用 root 权限运行：sudo bash uninstall.sh"
  exit 1
fi

# 1. 停止并禁用服务
if systemctl list-units --type=service --all | grep -q "$SERVICE_NAME"; then
  echo "[1/5] 停止并禁用 systemd 服务 ..."
  systemctl stop "$SERVICE_NAME" 2>/dev/null || true
  systemctl disable "$SERVICE_NAME" 2>/dev/null || true
else
  echo "[1/5] 服务不存在，跳过"
fi

# 2. 删除 systemd 服务文件
if [ -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
  echo "[2/5] 删除 systemd 服务文件 ..."
  rm -f "/etc/systemd/system/$SERVICE_NAME.service"
  systemctl daemon-reload
else
  echo "[2/5] systemd 服务文件不存在，跳过"
fi

# 3. 删除程序和数据目录
if [ -d "$INSTALL_DIR" ]; then
  echo "[3/5] 删除程序目录 $INSTALL_DIR ..."
  rm -rf "$INSTALL_DIR"
else
  echo "[3/5] 程序目录不存在，跳过"
fi

# 4. 删除用户和组
if id "$USER_NAME" &>/dev/null; then
  echo "[4/5] 删除运行用户 $USER_NAME ..."
  userdel "$USER_NAME" 2>/dev/null || true
else
  echo "[4/5] 用户 $USER_NAME 不存在，跳过"
fi

# 5. 清理防火墙规则（可选）
echo "[5/5] 检查防火墙规则 ..."
if command -v ufw &>/dev/null && ufw status | grep -q "8080/tcp"; then
  echo "      发现 ufw 规则 8080/tcp，建议手动删除：ufw delete allow 8080/tcp"
fi

echo ""
echo "=== 卸载完成 ==="
echo "如需保留数据库备份，请确认已备份 /opt/lan-manager/data/lan-manager.db"
echo ""
