#!/bin/bash
#
# zyhk_sio_client 卸载脚本
# 用法: sudo ./uninstall.sh
#

set -e

INSTALL_DIR="/opt/zyhk_sio_client"
SERVICE_NAME="zyhk-sio-client"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}[OK]${NC}   $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
err()   { echo -e "${RED}[ERR]${NC}  $*"; }

check_root() {
    if [ "$EUID" -ne 0 ]; then
        err "Please run as root: sudo $0"
        exit 1
    fi
}

remove_service() {
    if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
        info "Stopping service..."
        systemctl stop "$SERVICE_NAME"
    fi
    if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
        info "Disabling service..."
        systemctl disable "$SERVICE_NAME"
    fi
    if [ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]; then
        rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
        systemctl daemon-reload
        ok "Systemd service removed"
    fi
}

remove_files() {
    if [ -d "$INSTALL_DIR" ]; then
        read -p "Remove $INSTALL_DIR? [y/N] " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            rm -rf "$INSTALL_DIR"
            ok "Removed $INSTALL_DIR"
        else
            warn "Keeping $INSTALL_DIR"
        fi
    fi
}

remove_user() {
    if id -u "zyhk" &>/dev/null; then
        read -p "Remove user 'zyhk'? [y/N] " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            userdel "zyhk" 2>/dev/null || true
            ok "User 'zyhk' removed"
        fi
    fi
}

check_root
remove_service
remove_files
remove_user
ok "Uninstall complete"
