#!/bin/bash
#
# ZbxTable 一键安装脚本
# 使用方法: curl -s https://your-domain.com/install.sh | bash
# 或者: wget -qO- https://your-domain.com/install.sh | bash
#

set -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
ZBXTABLE_VERSION="latest"
DOWNLOAD_URL="https://dl.cactifans.com/zbxtable/zbxtable-latest-linux-amd64.tar.gz"
INSTALL_DIR="/usr/local/zbxtable"
SERVICE_USER="zbxtable"
SERVICE_GROUP="zbxtable"
HTTP_PORT="8088"

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为 root 用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        print_error "此脚本需要 root 权限运行"
        print_info "请使用 sudo 运行: sudo bash install.sh"
        exit 1
    fi
}

# 检测操作系统
detect_os() {
    print_info "检测操作系统..."
    
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        OS=$ID
        OS_VERSION=$VERSION_ID
    elif [[ -f /etc/redhat-release ]]; then
        OS="centos"
    else
        print_error "无法检测操作系统类型"
        exit 1
    fi
    
    print_success "操作系统: $OS $OS_VERSION"
}

# 检查系统要求
check_requirements() {
    print_info "检查系统要求..."
    
    # 检查 systemd
    if ! command -v systemctl &> /dev/null; then
        print_error "系统不支持 systemd"
        exit 1
    fi
    
    # 检查端口是否被占用
    if netstat -tuln 2>/dev/null | grep -q ":${HTTP_PORT} " || ss -tuln 2>/dev/null | grep -q ":${HTTP_PORT} "; then
        print_warning "端口 ${HTTP_PORT} 已被占用"
        read -p "是否继续安装？(y/n): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
    
    print_success "系统要求检查通过"
}

# 检查必要工具
check_tools() {
    print_info "检查必要工具..."
    
    local missing_tools=()
    
    # 检查 curl 或 wget
    if ! command -v curl &> /dev/null && ! command -v wget &> /dev/null; then
        missing_tools+=("curl 或 wget")
    fi
    
    if [ ${#missing_tools[@]} -gt 0 ]; then
        print_error "缺少必要工具: ${missing_tools[*]}"
        print_info "请先安装: apt-get install curl 或 yum install curl"
        exit 1
    fi
    
    print_success "必要工具检查通过"
}

# 创建系统用户
create_user() {
    print_info "创建系统用户 ${SERVICE_USER}..."
    
    if id "$SERVICE_USER" &>/dev/null; then
        print_warning "用户 ${SERVICE_USER} 已存在"
    else
        useradd -r -s /sbin/nologin -M "$SERVICE_USER"
        print_success "用户 ${SERVICE_USER} 创建成功"
    fi
}

# 下载 ZbxTable
download_zbxtable() {
    print_info "下载 ZbxTable ${ZBXTABLE_VERSION}..."
    
    # 创建临时目录
    TMP_DIR=$(mktemp -d)
    cd "$TMP_DIR"
    
    # 下载压缩包
    if ! curl -fsSL -o zbxtable.tar.gz "$DOWNLOAD_URL"; then
        print_error "下载失败，请检查网络连接或下载地址"
        rm -rf "$TMP_DIR"
        exit 1
    fi
    
    # 验证文件
    if [[ ! -s zbxtable.tar.gz ]]; then
        print_error "下载的文件为空"
        rm -rf "$TMP_DIR"
        exit 1
    fi
    
    # 解压文件
    print_info "解压文件..."
    if ! tar -xzf zbxtable.tar.gz; then
        print_error "解压失败"
        rm -rf "$TMP_DIR"
        exit 1
    fi
    
    # 查找解压后的目录（支持任意版本号）
    EXTRACT_DIR=$(find . -maxdepth 1 -type d -name "zbxtable-*-linux-amd64" | head -n 1)
    
    if [[ -z "$EXTRACT_DIR" ]]; then
        print_error "未找到解压目录"
        rm -rf "$TMP_DIR"
        exit 1
    fi
    
    # 验证二进制文件是否存在
    if [[ ! -f "$EXTRACT_DIR/zbxtable" ]]; then
        print_error "解压后未找到 zbxtable 二进制文件"
        rm -rf "$TMP_DIR"
        exit 1
    fi
    
    # 将二进制文件移到临时目录根目录，方便后续安装
    mv "$EXTRACT_DIR/zbxtable" ./zbxtable
    
    print_success "ZbxTable 下载完成"
}

# 安装 ZbxTable
install_zbxtable() {
    print_info "安装 ZbxTable 到 ${INSTALL_DIR}..."
    
    # 检查服务是否存在并记录状态
    local SERVICE_WAS_RUNNING=false
    if systemctl list-unit-files | grep -q "zbxtable.service"; then
        print_info "检测到已安装的 ZbxTable 服务"
        if systemctl is-active --quiet zbxtable 2>/dev/null; then
            SERVICE_WAS_RUNNING=true
            print_info "停止旧服务..."
            systemctl stop zbxtable
        fi
    fi
    
    # 创建安装目录（程序会自动创建 config、log、data、download 等子目录）
    mkdir -p "$INSTALL_DIR"
    
    # 复制文件
    cp zbxtable "$INSTALL_DIR/"
    chmod +x "$INSTALL_DIR/zbxtable"
    
    # 设置权限
    chown -R "$SERVICE_USER:$SERVICE_GROUP" "$INSTALL_DIR"
    
    # 清理临时文件
    cd /
    rm -rf "$TMP_DIR"
    
    print_success "ZbxTable 安装完成"
    
    # 如果之前服务在运行，自动重启
    if [ "$SERVICE_WAS_RUNNING" = true ]; then
        print_info "检测到系统使用 systemd，准备自动重启服务..."
        sleep 1
        
        # 重载 systemd 配置
        systemctl daemon-reload
        
        # 重启服务
        if systemctl restart zbxtable; then
            print_success "ZbxTable 服务已自动重启"
            
            # 等待服务启动
            sleep 2
            
            # 检查服务状态
            if systemctl is-active --quiet zbxtable; then
                print_success "服务运行正常"
            else
                print_warning "服务重启后状态异常，请检查日志"
                print_info "查看日志: journalctl -u zbxtable -f"
            fi
        else
            print_error "服务重启失败，请手动重启"
            print_info "手动重启: systemctl restart zbxtable"
        fi
    fi
}

# 创建 systemd 服务文件
create_systemd_service() {
    print_info "创建 systemd 服务..."
    
    # 预先创建必要的目录
    print_info "创建必要的目录..."
    mkdir -p "${INSTALL_DIR}/config"
    mkdir -p "${INSTALL_DIR}/log"
    mkdir -p "${INSTALL_DIR}/data"
    mkdir -p "${INSTALL_DIR}/download"
    
    # 设置目录权限
    chown -R "${SERVICE_USER}:${SERVICE_GROUP}" "${INSTALL_DIR}"
    chmod -R 755 "${INSTALL_DIR}"
    
    cat > /etc/systemd/system/zbxtable.service << EOF
[Unit]
Description=ZbxTable - Zabbix Monitoring Tool
Documentation=https://github.com/canghai908/zbxtable
After=syslog.target network.target

[Service]
Type=simple
User=${SERVICE_USER}
Group=${SERVICE_GROUP}
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/zbxtable web
ExecReload=/bin/kill -HUP \$MAINPID

# 自动重启配置
Restart=on-failure
RestartSec=5s

# 进程管理
KillMode=mixed
KillSignal=SIGTERM
TimeoutStopSec=10
TimeoutStartSec=30

# 资源限制
LimitNOFILE=65535
LimitNPROC=65535

# 日志
StandardOutput=journal
StandardError=journal
SyslogIdentifier=zbxtable

[Install]
WantedBy=multi-user.target
EOF
    
    # 验证二进制文件
    if [[ ! -f "${INSTALL_DIR}/zbxtable" ]]; then
        print_error "二进制文件不存在: ${INSTALL_DIR}/zbxtable"
        exit 1
    fi
    
    if [[ ! -x "${INSTALL_DIR}/zbxtable" ]]; then
        print_error "二进制文件没有执行权限: ${INSTALL_DIR}/zbxtable"
        chmod +x "${INSTALL_DIR}/zbxtable"
        print_info "已添加执行权限"
    fi
    
    # 重载 systemd
    systemctl daemon-reload
    
    print_success "systemd 服务创建完成"
}

# 配置防火墙
configure_firewall() {
    print_info "配置防火墙..."
    
    # firewalld (CentOS/RHEL)
    if command -v firewall-cmd &> /dev/null && systemctl is-active --quiet firewalld; then
        firewall-cmd --permanent --add-port=${HTTP_PORT}/tcp > /dev/null 2>&1
        firewall-cmd --reload > /dev/null 2>&1
        print_success "firewalld 规则已添加"
    # ufw (Ubuntu/Debian)
    elif command -v ufw &> /dev/null && ufw status | grep -q "Status: active"; then
        ufw allow ${HTTP_PORT}/tcp > /dev/null 2>&1
        print_success "ufw 规则已添加"
    else
        print_warning "未检测到防火墙或防火墙未启用"
    fi
}

# 启动服务
start_service() {
    # 检查服务是否已经在运行（由 install_zbxtable 自动重启的）
    if systemctl is-active --quiet zbxtable; then
        print_info "服务已在运行中，跳过启动步骤"
        return 0
    fi
    
    print_info "启动 ZbxTable 服务..."
    
    # 启用开机自启
    systemctl enable zbxtable > /dev/null 2>&1
    
    # 启动服务
    if systemctl start zbxtable; then
        print_success "ZbxTable 服务启动成功"
    else
        print_error "ZbxTable 服务启动失败"
        print_info "查看日志: journalctl -u zbxtable -f"
        exit 1
    fi
    
    # 等待服务启动
    sleep 2
    
    # 检查服务状态
    if systemctl is-active --quiet zbxtable; then
        print_success "ZbxTable 服务运行正常"
    else
        print_error "ZbxTable 服务未正常运行"
        print_info "查看状态: systemctl status zbxtable"
        exit 1
    fi
}

# 获取本机 IP
get_local_ip() {
    # 尝试多种方法获取 IP
    LOCAL_IP=$(ip route get 1 2>/dev/null | awk '{print $7}' | head -n1)
    
    if [[ -z "$LOCAL_IP" ]]; then
        LOCAL_IP=$(hostname -I 2>/dev/null | awk '{print $1}')
    fi
    
    if [[ -z "$LOCAL_IP" ]]; then
        LOCAL_IP="localhost"
    fi
    
    echo "$LOCAL_IP"
}

# 打印安装信息
print_install_info() {
    LOCAL_IP=$(get_local_ip)
    
    # 检查是否为更新安装
    local IS_UPDATE=false
    if systemctl list-unit-files | grep -q "zbxtable.service" && systemctl is-active --quiet zbxtable; then
        IS_UPDATE=true
    fi
    
    echo
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    if [ "$IS_UPDATE" = true ]; then
        print_success "ZbxTable 更新完成并已自动重启！"
    else
        print_success "ZbxTable 安装完成！"
    fi
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo
    echo -e "${GREEN}📦 安装信息:${NC}"
    echo "   安装目录: ${INSTALL_DIR}"
    echo "   配置文件: ${INSTALL_DIR}/config/app.conf"
    echo "   日志目录: ${INSTALL_DIR}/log"
    echo "   服务用户: ${SERVICE_USER}"
    echo
    echo -e "${GREEN}🌐 访问地址:${NC}"
    if [ "$IS_UPDATE" = true ]; then
        echo "   本地访问: http://localhost:${HTTP_PORT}"
        echo "   局域网访问: http://${LOCAL_IP}:${HTTP_PORT}"
    else
        echo "   本地访问: http://localhost:${HTTP_PORT}/install"
        echo "   局域网访问: http://${LOCAL_IP}:${HTTP_PORT}/install"
    fi
    echo
    echo -e "${GREEN}🔧 常用命令:${NC}"
    echo "   启动服务: systemctl start zbxtable"
    echo "   停止服务: systemctl stop zbxtable"
    echo "   重启服务: systemctl restart zbxtable"
    echo "   查看状态: systemctl status zbxtable"
    echo "   查看日志: journalctl -u zbxtable -f"
    echo "   查看日志: tail -f ${INSTALL_DIR}/log/\$(date +%Y-%m-%d).log"
    echo
    if [ "$IS_UPDATE" = false ]; then
        echo -e "${GREEN}📝 下一步操作:${NC}"
        echo "   1. 访问安装页面完成初始化配置"
        echo "   2. 配置数据库连接信息"
        echo "   3. 完成安装后执行: systemctl restart zbxtable"
        echo "   4. 使用默认账号登录: admin / Zbxtable"
        echo
    else
        echo -e "${GREEN}✅ 更新说明:${NC}"
        echo "   - 服务已自动重启，配置文件保持不变"
        echo "   - 如有问题请查看日志: journalctl -u zbxtable -f"
        echo
    fi
    echo -e "${YELLOW}⚠️  安全提示:${NC}"
    echo "   - 首次登录后请立即修改默认密码"
    echo "   - 建议配置 Nginx 反向代理并启用 HTTPS"
    echo "   - 定期备份数据库和配置文件"
    echo
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo
}

# 主函数
main() {
    echo
    
    check_root
    detect_os
    check_requirements
    check_tools
    create_user
    download_zbxtable
    install_zbxtable
    create_systemd_service
    configure_firewall
    start_service
    print_install_info
}

# 执行主函数
main
