#!/bin/bash

# --- 全局变量和颜色定义 ---
YELLOW='\033[0;33m'
GREEN='\033[0;32m'
NC='\033[0m'

# 用于存储检测结果的全局变量
HAS_JQ=false
IS_ROOT=false
DISTRO_ID="未知"
SYSTEM_PRETTY_NAME="未知"

# 统一的输出函数
print_info() {
    local label="$1"
    local value="$2"
    echo -e "${YELLOW}${label}:${NC} ${GREEN}${value}${NC}"
}

# 操作系统识别函数
detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        SYSTEM_PRETTY_NAME="$PRETTY_NAME"
        DISTRO_ID="$ID"
    elif command -v lsb_release &> /dev/null; then
        SYSTEM_PRETTY_NAME=$(lsb_release -ds)
        DISTRO_ID=$(lsb_release -is | tr '[:upper:]' '[:lower:]')
    elif [ -f /etc/debian_version ]; then
        DISTRO_ID="debian"
        SYSTEM_PRETTY_NAME="Debian $(cat /etc/debian_version)"
    fi
}

# jq 安装函数
install_jq() {
    if [[ "$DISTRO_ID" == "ubuntu" || "$DISTRO_ID" == "debian" ]]; then
        echo "--> 检测到 Debian/Ubuntu 系统，使用 apt-get..."
        apt-get update > /dev/null && apt-get install -y jq
    elif [[ "$DISTRO_ID" == "centos" || "$DISTRO_ID" == "rhel" || "$DISTRO_ID" == "fedora" || "$DISTRO_ID" == "rocky" ]]; then
        echo "--> 检测到 RHEL/CentOS/Fedora 等系统..."
        command -v dnf &> /dev/null && dnf install -y jq || yum install -y jq
    else
        echo "--> 无法识别的发行版 ($DISTRO_ID)，请手动安装 'jq'。"
        return 1
    fi
}

# 主程序：显示所有系统信息
main_display() {
    echo
    echo "=============== 系统信息概览 ==============="
    
    # --- 1. 系统状态与负载 ---
    echo
    uptime_seconds=$(cut -d. -f1 /proc/uptime)
    days=$((uptime_seconds / 60 / 60 / 24))
    hours=$(( (uptime_seconds / 60 / 60) % 24 ))
    minutes=$(( (uptime_seconds / 60) % 60 ))
    print_info "系统已运行时间" "$days 天 $hours 小时 $minutes 分钟"
    print_info "系统平均负载" "$(uptime | awk -F'load average: ' '{print $2}')"
    print_info "当前登录用户数" "$(who | wc -l)"

    # --- 2. 硬件与虚拟化 ---
    echo
    print_info "CPU型号" "$(grep "model name" /proc/cpuinfo | uniq | awk -F': ' '{print $2}')"
    print_info "CPU核心数" "$(grep -c processor /proc/cpuinfo)"
    print_info "系统内存" "$(free -h | awk '/^Mem:/ {print $2}')"
    virt_tech="未知"
    if command -v systemd-detect-virt &> /dev/null && [ "$(systemd-detect-virt)" != "none" ]; then
        virt_tech=$(systemd-detect-virt)
    elif grep -q 'hypervisor' /proc/cpuinfo; then
        virt_tech="检测到 Hypervisor (KVM/VMware等)"
    elif [ -f /.dockerenv ]; then
        virt_tech="Docker 容器"
    else
        virt_tech="物理机或未知"
    fi
    print_info "虚拟化技术" "$virt_tech"
    print_info "根目录磁盘使用" "$(df -h / | awk 'NR==2 {print $3 "/" $2 " (" $5 ")"}')"

    # --- 4. 系统与内核 ---
    echo
    print_info "系统版本" "${SYSTEM_PRETTY_NAME}"
    print_info "发行版ID" "${DISTRO_ID}"
    print_info "内核版本" "$(uname -r)"
    print_info "系统架构" "$(uname -m)"

    # --- 5. 网络信息 ---
    echo
    if [ "$HAS_JQ" = true ]; then
        ip_info_json=$(curl -s --max-time 10 "ipinfo.io?token=caf98a1170550b")
        if [ -n "$ip_info_json" ] && ! echo "$ip_info_json" | jq -e '.error' > /dev/null; then
            public_ip=$(echo "$ip_info_json" | jq -r '.ip')
            org=$(echo "$ip_info_json" | jq -r '.org')
            location="$(echo "$ip_info_json" | jq -r '.city'), $(echo "$ip_info_json" | jq -r '.region') ($(echo "$ip_info_json" | jq -r '.country'))"
            print_info "公网 IP" "$public_ip"
            print_info "地理位置" "$location"
            print_info "运营商" "$org"
        else
            print_info "网络信息" "无法从 ipinfo.io 获取"
        fi
    else
        print_info "网络信息" "查询失败, 'jq' 工具缺失"
    fi
    echo
    echo "=========================================="
}


# ================================================
#               脚本主执行流程
# ================================================

# 步骤 1: 识别操作系统
clear
detect_os

# 步骤 2: 检查环境
[ "$EUID" -eq 0 ] && IS_ROOT=true
command -v jq &> /dev/null && HAS_JQ=true
# 步骤 3: 处理依赖
if [ "$HAS_JQ" = false ]; then
    echo
    echo -e "${YELLOW}依赖工具 'jq' 未安装。${NC}"
    if [ "$IS_ROOT" = true ]; then
        echo -e "${GREEN}检测到 root 权限，正在尝试自动安装...${NC}"
        install_jq
        # 再次检查，更新依赖状态
        if command -v jq &> /dev/null; then
            echo -e "${GREEN}jq 安装成功！${NC}"
            HAS_JQ=true
            clear
        else
            echo -e "${YELLOW}jq 自动安装失败，请手动安装。${NC}"
        fi
    else
        echo -e "${YELLOW}请使用 'sudo' 运行此脚本以自动安装 'jq'，或手动安装。${NC}"
    fi
fi

# 步骤 4: 执行主程序
main_display

exit 0