#!/bin/bash
#region //定义颜色
white='\033[0m'
green='\033[0;32m'
blue='\033[0;34m'
red='\033[31m'
yellow='\033[33m'
grey='\e[37m'
pink='\033[38;5;218m'
cyan='\033[96m'
pink='\033[0;35m'

# 检查是否以 root 权限执行
if [ "$EUID" -ne 0 ]; then
  echo "请使用 sudo 或以 root 用户执行此脚本。 "
  echo -e "执行命令：${red}sudo ./1.JC系统信息查询.sh${white}"
  exit 1
fi

# 系统信息查询
system_info() {

    clear
    #activation=$(sudo kylin_activation_check | tail -n 1)
    #eval $(ip link show | awk '/^[0-9]+: / { iface=$2 } /link/ { if (iface !~ /lo/) { gsub(":", "", iface); print "interface=" iface "\nmac_address=" $2 } }') 
   ip_dev_mac=$(ip link show | awk ' /^[0-9]+: / { iface=$2 }  /link/ {  if (iface !~ /lo/ && iface ~ /^e/) { gsub(":", "", iface);count++;printf "\033[31m网卡%d: %s\nMAC地址: %s\n\n", count, iface, iface, $2; }}')
    eval $(ifconfig $dev_name | awk -v ip=ip '/inet /{printf "ip=%s;mask=%s",$2,$4}')
    eval $(ip route show default | awk '{printf "gateway=%s",$3}')
    #mac=$(ip addr show $dev_name | grep 'link/ether' | cut -d ' ' -f 6)
    format=$(grep "^nameserver " /etc/resolv.conf | grep -v "127.0.0." | awk '{count++;printf "DNS%s:%s\n",count,$2}')
    disk_info=$(lsblk | grep "disk" | awk '{count++; printf "磁盘%d(%s): %s\n",count,$1,$4}')
    sn=$(lsblk -o NAME,SERIAL | grep -E '^(sd|nvme)' | awk '{count++;printf "序列号%d(%s): %s\n", count,$1, $2}')
    #ipv4_address=$(curl -s --max-time 1 ipv4.ip.sb)
    #ipv6_address=$(curl -s --max-time 1 ipv6.ip.sb)
    #cpu_info=$(lscpu | awk -F': +' '/Model name:/ {print $2; exit}')
   cpu_info=$( grep "model name" /proc/cpuinfo | uniq | sed -e 's/model name\t: //')
   cpu_usage_percent=$(awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else printf "%.0f\n", (($2+$4-u1) * 100 / (t-t1))}' \
        <(grep 'cpu ' /proc/stat) <(sleep 1; grep 'cpu ' /proc/stat))

    user_name=$(who | awk '{print $1}' | head -n 1)
    os_install_path=$(df | awk '{if($6=="/"){print $1}}')
    src_time=$(tune2fs -l $os_install_path | grep "^Filesystem created" | sed -e 's/^Filesystem created:[ ]*//')
    dst_time=$(date -d "$src_time" +"%Y-%m-%d（%A） %H:%m:%S")
    cpu_cores=$(nproc)
    mem_size=$(grep "^MemTotal:" /proc/meminfo | awk '{printf "%.f",$2/1024/1024}')
    mem_info=$(free -b | awk 'NR==2{printf "%.2f/%.2f MB (%.2f%%)", $3/1024/1024, $2/1024/1024, $3*100/$2}')
    disk_info1=$(df -h | awk '$NF=="/"{printf "%s/%s (%s)", $3, $2, $5}')
    disk_info2=$(df -h | awk '$NF=="/data"{printf "%s/%s (%s)", $3, $2, $5}')
    #ipinfo=$(curl -s ipinfo.io)
    #country=$(echo "$ipinfo" | grep 'country' | awk -F': ' '{print $2}' | tr -d '",')
    #city=$(echo "$ipinfo" | grep 'city' | awk -F': ' '{print $2}' | tr -d '",')
    city=$(timedatectl | grep 'Time zone' | awk '{print $3}')
    #isp_info=$(echo "$ipinfo" | grep 'org' | awk -F': ' '{print $2}' | tr -d '",')
    cpu_arch=$(uname -m)
    hostname=$(hostname)
    kernel_version=$(uname -r)
    #congestion_algorithm=$(sysctl -n net.ipv4.tcp_congestion_control)
    queue_algorithm=$(sysctl -n net.core.default_qdisc)
    #os_info=$(grep PRETTY_NAME /etc/os-release | cut -d '=' -f2 | tr -d '"')
    os_info=$(awk -F "=" '/^VERSION=/{sub(/^"/,"",$2);sub(/"$/,"",$2);print $2}' /etc/os-release)
    #os_release_id=$(awk -F "=" '/RELEASE_ID/{sub(/^"/,"",$2);sub(/"$/,"",$2);print $2}' /etc/os-release)
    os_release_id=$(cat /etc/.kyinfo | sed -n 's/.*dist_id=\([^ ]*\).*/\1/p')
    output=$(awk 'BEGIN { rx_total = 0; tx_total = 0 }
        NR > 2 { rx_total += $2; tx_total += $10 }
        END {
            rx_units = "Bytes";
            tx_units = "Bytes";
            if (rx_total > 1024) { rx_total /= 1024; rx_units = "KB"; }
            if (rx_total > 1024) { rx_total /= 1024; rx_units = "MB"; }
            if (rx_total > 1024) { rx_total /= 1024; rx_units = "GB"; }

            if (tx_total > 1024) { tx_total /= 1024; tx_units = "KB"; }
            if (tx_total > 1024) { tx_total /= 1024; tx_units = "MB"; }
            if (tx_total > 1024) { tx_total /= 1024; tx_units = "GB"; }

            printf("总接收: %.2f %s\n总发送: %.2f %s\n", rx_total, rx_units, tx_total, tx_units);
        }' /proc/net/dev)

    current_time=$(date +"%Y-%m-%d %H:%M" | sed 's/^\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\} [0-9]\{2\}:[0-9]\{2\}\)/\1/')
    swap_info=$(free -m | awk 'NR==3{used=$3; total=$2; if (total == 0) {percentage=0} else {percentage=used*100/total}; printf "%dMB/%dMB (%d%%)", used, total, percentage}')
    runtime=$(cat /proc/uptime | awk -F. '{run_days=int($1 / 86400);run_hours=int(($1 % 86400) / 3600);run_minutes=int(($1 % 3600) / 60); if (run_days > 0) printf("%d天 ", run_days); if (run_hours > 0) printf("%d时 ", run_hours); printf("%d分\n", run_minutes)}')
    timezone=$(timedatectl | grep "Time zone" | awk '{print $3}')
 
manufacturer=$(sudo dmidecode -t system | grep -i 'Manufacturer' | sed 's/Manufacturer: //' | sed 's/^[ \t]*//')
product=$(sudo dmidecode -t system | grep -i 'Product Name' | sed 's/Product Name: //' | sed 's/^[ \t]*//')
version=$(sudo dmidecode -t system | grep  Version | sed 's/Version: //' | sed 's/^[ \t]*//')


    echo ""
    echo -e "${red}===============系统信息查询===============${white}"
    echo ""
    echo -e "${pink}==============   KYLIN   ==============${white}"
    echo ""
    echo -e "${pink}================机器信息================${white}"
    echo "主机品牌: $manufacturer"
    echo "主机产品: $product"
    echo "版本号: $version"
    echo -e "${pink}================版本信息================${white}"
    echo "系统版本: $os_info"
    echo "版本号: $os_release_id"
    echo "内核: $kernel_version"
   echo -e "${pink}================安装信息================${white}"
    echo "安装时间: $dst_time"
    echo "主机名: $hostname"
    echo "用户名: $user_name"
    echo -e "${pink}================CPU信息================${white}"
    echo "CPU架构: $cpu_arch"
    echo "CPU型号: $cpu_info"
    echo "CPU核心数: $cpu_cores"
    echo "CPU占用: $cpu_usage_percent%"
    echo -e "${pink}================内存信息================${white}"
    #echo "内存大小: ${mem_size}G"
    echo "物理内存: $mem_info"
    echo "虚拟内存: $swap_info"
    echo -e "${pink}================硬盘信息================${white}"
    echo "$disk_info"   
    echo "$sn"  
    echo "根分区占用: $disk_info1"
    echo "数据盘占用: $disk_info2"
    echo -e "${pink}================流量信息================${white}"
    echo "$output"
    #echo -e "${pink}================算法信息================${white}"
    #echo "网络拥堵算法: $congestion_algorithm $queue_algorithm"
    echo -e "${pink}================网络信息================${white}"
 # 函数：将CIDR格式的子网掩码转换为点分十进制格式
cidr_to_netmask() {
    local cidr=$1
    local mask=""
    for i in $(seq 0 3); do
        local shift=$(( (3 - i) * 8 ))
        local octet=$(( (0xFFFFFFFF << (32 - cidr) >> shift) & 0xFF ))
        mask="${mask}${octet}"
        if [ $i -ne 3 ]; then
            mask="${mask}."
        fi
    done
    echo $mask
}

for iface in $(ip link show | awk '/^[0-9]+: / { iface=$2 } /link/ { if (iface !~ /lo/ && iface ~ /^e/) { gsub(":", "", iface); print iface } }'); do
    # 获取 IP 地址
    ip_addr=$(ip addr show $iface | awk -F 'inet ' '/inet /{print $2}' | awk '{print $1}' | awk -F '/' '{print $1}')
    
    # 获取子网掩码
    if [ -n "$ip_addr" ]; then
        netmask_bits=$(ip addr show $iface | grep 'inet ' | awk '{print $2}' | awk -F '/' '{print $2}')
        netmask=$(cidr_to_netmask $netmask_bits)
    else
        netmask="无"
    fi
    
    # 获取网关
    gateway=$(ip route show dev $iface | awk '/default/ {print $3}')
    
    # 获取 MAC 地址
    mac_addr=$(ip link show $iface | awk '/link\/ether/ {print $2}')

    echo "网卡: $iface"
    echo "MAC地址: $mac_addr"
    echo "IP地址: ${ip_addr:-无}"
    echo "子网掩码: ${netmask:-无}"
    echo "网关: ${gateway:-无}"
    echo
done
   #echo "网络接口名: $interface"
   #echo "$ip_dev_mac"
    #echo "IP地址: $ip"
    #echo "mac地址: $mac_address"
    #echo "子网掩码: $mask"
    #echo "网关: $gateway"
    echo "$format"    
    echo -e "${pink}================时区信息================${white}"
    #echo "地理位置: $country $city"
    echo "系统时区: $timezone"
    echo "系统时间: $current_time"
    echo -e "${pink}================运行时长================${white}"
    echo "系统运行时长: $runtime"
    echo

}

# 调用函数
system_info
