#!/bin/env bash

set +u 

<<COMMENT
This script is help system administrators deal with some repetitive tasks.
Author: changming
Created: 2021-01-21 11:39:00
COMMENT


# 0.Set environment
export LANG=C
export PATH=/bin/:/sbin:/usr/bin/:/usr/sbin:/usr/local/sbin/:/usr/local/bin/:$PATH
CURTIME=$(date +%Y%m%d%H%M%S)
WORKDIR=$(mkdir -p /tmp/hwInfo_${CURTIME} && cd /tmp/hwInfo_${CURTIME} && pwd)
step=0
report_time=$(date +%F" "%T)
source /etc/profile
#source /etc/init.d/functions
download_server="tw15b0178.onething.net"
logfile=$(echo "${WORKDIR}/sas2ircu.log${step}")


# basic_env_setup
basic_env_setup(){ 
    # Set dns
    ping -c 3 -w 3  www.xunlei.com &>/dev/null
    if [ $? -ne 0 ];then
        echo -e "nameserver 114.114.114.114\nnameserver 223.5.5.5" > /etc/resolv.conf 
    fi    
    # Setup yum repo
    if [ ! -e /var/lock/yum.pid ];then
        if [ ${os_type} -eq 0 ];then
            command  -v wget &>/dev/null || yum  -y install  wget &>/dev/null
            mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo_backup_`date +%F-%H-%M-%S`
            wget http://centos.yum.sandai.net/.help/CentOS-Base7.repo -O /etc/yum.repos.d/CentOS-Base.repo -o /dev/null &>/dev/null
            rpm -ivh http://centos.yum.sandai.net/epel/epel-release-latest-7.noarch.rpm  &>/dev/null
            mv /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel.repo_backup_`date +%F-%H-%M-%S`
            wget http://centos.yum.sandai.net/.help/epel7.repo -O /etc/yum.repos.d/epel.repo -o /dev/null &>/dev/null
            wget http://centos.yum.sandai.net/epel/RPM-GPG-KEY-EPEL-7 -O /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 -o /dev/null &>/dev/null
            yum clean all &>/dev/null
            yum makecache &>/dev/null
            yum install epel-release -y &>/dev/null
            touch /var/lock/yum.pid
        elif [ ${os_type} -eq 1 ];then
            apt update &>/dev/null 
            touch /var/lock/yum.pid
        fi
    fi
}

# Install basic packages
basic_install_pack(){
    if [ ${os_type} -eq 0 ];then 
        command -v ipmitool &>/dev/null ||  yum -y install ipmitool &>/dev/null && service ipmi start &>/dev/null
        command -v hdparm &>/dev/null || yum  -y install  hdparm &>/dev/null
        command -v lshw &>/dev/null || yum  -y install  lshw &>/dev/null
        command -v lldpad &>/dev/null || yum  -y install  lldpad &>/dev/null
    elif [ ${os_type} -eq 1 ];then 
        command -v ipmitool &>/dev/null ||  apt -y install ipmitool &>/dev/null && service ipmi start &>/dev/null
        command -v hdparm &>/dev/null || apt -y install  hdparm &>/dev/null
        command -v lshw &>/dev/null || apt  -y install  lshw &>/dev/null
        command -v lldpad &>/dev/null || apt  -y install  lldpad &>/dev/null
    fi
}

# Get summary
get_summary(){
    # Summ
    man=$(dmidecode -t 1 | grep Manufacturer | awk -F":" '{print$2}' | sed s#[[:space:]]##g)
    model=$(dmidecode  -t 1 | grep 'Product Name' | awk -F':' '{print$2}'| sed s#^[[:space:]]##g)
    sn=$(dmidecode -s system-serial-number | sed s#[[:space:]]##g)
    u_wei=$(curl -sL http://wx:WXxunlei123$%^@${download_server}:9090/other/tool/scripts/shell/hwCollect/server_hardware_height.cnf | grep  "^${model}" | awk -F"=" '{print$NF}')
    hostname=$(hostname)
    wip=$(for i in `seq 3`;do timeout 5 curl -sL myip.ipip.net | awk '{print$2,$4,$5,$6}';done | sort | head -n 1 2>/dev/null)
    ipmi_ip=$(ipmitool lan print | grep  "^IP Address  " | awk '{print$NF}')
    
    if [ ${os_type} -eq 0 ];then
        os_version=$(cat /etc/redhat-release)
    elif [ ${os_type} -eq 1 ];then
        os_version=$(echo "debian "$(cat /etc/debian_version))
    fi 

    kernel=$(uname -r)
    uptime=`cat /proc/uptime | cut -f1 -d.`
    upDays=$((uptime/60/60/24))
    upHours=$((uptime/60/60%24))
    upMins=$((uptime/60%60))
    upSecs=$((uptime%60))   

    echo -e "==========\033[34mLocal server hardware information(${report_time:-"N/A"})\033[0m=========="
    echo -e "Manufacturer: \t${man:-"N/A"}"
    echo -e "Model: \t\t$model \033[1;32m${u_wei:-"N/A"}\033[0m"
    echo -e "SN: \t\t${sn:-"N/A"}"
    echo -e "HOstname: \t${hostname:-"N/A"}"
    echo -e "WANIP/ISP: \t${wip:-"N/A"}"
    echo -e "IPMI_IP: \t${ipmi_ip:-"N/A"}"
    echo -e "OS: \t\t${os_version:-"N/A"}"
    echo -e "Kernel: \t${kernel:-"N/A"}"
    echo -e "Runtime: \t${upDays:-"N/A"} days ${upHours:-"N/A"} hours ${upMins:-"N/A"} mins ${upSecs:-"N/A"} sesc"
}

# Get CPU 
get_cpu(){
    cpu_model=$(lscpu | grep "Model name" | awk -F":" '{print$2}'| sed s#[[:space:]]##g)
    cpu_thread="$(lscpu | grep '^CPU(' | awk -F":" '{print$2}' | sed s#[[:space:]]##g)c"
    cpu_Virtualization=$(lscpu | grep 'Virtualization' | awk -F":" '{print$2}' | sed s#[[:space:]]##g)
    cpu_max_speed=$(dmidecode  -t processor  | grep "Max Speed" | head -n1 | awk -F":" '{print$2}' | sed s#[[:space:]]##g)
    cpu_curr_speed=$(dmidecode  -t processor  | grep "Current Speed" | head -n1 | awk -F":" '{print$2}' | sed s#[[:space:]]##g)
    cpu_physics_total=$(dmidecode  -t processor | grep "^Handle" -c | sed s#[[:space:]]##g)
    cpu_governor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null)
    
    echo -e "CPU: \t\tSummary model:${cpu_model:-"N/A"} thread:\033[1;32m${cpu_thread:-"N/A"}\033[0m physics total:${cpu_physics_total:-"N/A"} virt:${cpu_Virtualization:-"N/A"} / max speed:${cpu_max_speed:-"N/A"} / cur speed:${cpu_curr_speed:-"N/A"}" / governor:${cpu_governor:-"N/A"} 
}

# Get mem
get_mem(){
    mem_total=$(cat /proc/meminfo | grep MemTotal | awk '{print int($2/1024/1000)"G"}')
    mem_grain=$(dmidecode -t memory | grep  -i size | awk ' $2 ~ /^[0-9]+$/ {print$2$3}' | sort | uniq  -c |sed -e 's/^[ ]*//g'  -e s#[[:space:]]#*#g | tr '\n' ' ')
    mem_max_cap=$(dmidecode -t memory | grep "Maximum Capacity" | awk '{print$3$4}'| sort  -n | uniq  -c | sed  -e 's#^[ ]*##g'  -e s#[[:space:]]#*#g)
    mem_number_devices=$(dmidecode -t memory | grep "Number Of Devices" | awk -F":" '{print$2}' | sort  -n | uniq  -c | sed  -e 's#^[ ]*##g' -e 's#  #*#g' | tr '\n' ' ')
    for i in  $(dmidecode -t memory  | grep "^Handle" | awk -F '[ ,]+' '{print$2}');do 
       mem_size=$(dmidecode -t memory | grep -A22 $i | grep  -i size | awk '{print$2}')
       expr 1 "+" $mem_size &>/dev/null
       if [ $? -eq 0 ];then
           echo "$i "$(dmidecode -t memory | grep -A22 $i  | grep -E "Size|Locator|Type|Speed|Manufacturer|Part Number|Serial Number" | egrep -v "Bank Locator|Type Detail|Configured Clock Speed|Configured Memory Speed" | sed s#[[:space:]]##g | xargs -n 6 )>> /${WORKDIR}/memory_details.txt
       else
           continue  
       fi
    done
 
    echo -e "Mem: \t\tSummary total:\033[1;32m${mem_total:-"N/A"}\033[0m / Number of Physics:${mem_grain:-"N/A"} / Maximum Capacity:${mem_max_cap:-"N/A"} / number of devices:${mem_number_devices:-"N/A"}"
    while read line;do
        echo -e "Mem:\t\t${line:-"N/A"}"
    done < /${WORKDIR}/memory_details.txt
}

# Install MegaCli64
install_megacli64(){
    wget -O /tmp/ibm_utl_sraidmr_megacli-8.00.48_linux_32-64.zip  http://thunder:xunlei@apt.sandai.net/tmp/ks/ibm_utl_sraidmr_megacli-8.00.48_linux_32-64.zip &>/dev/null
    unzip ibm_utl_sraidmr_megacli-8.00.48_linux_32-64.zip &>/dev/null
    cd linux/
    rpm  -ivh  *.rpm &>/dev/null
    cp -rf /opt/MegaRAID/MegaCli/MegaCli64 /usr/local/bin/MegaCli64 &>/dev/null
    chmod +x /opt/MegaRAID/MegaCli/MegaCli64 /usr/local/bin/MegaCli64 &>/dev/null
}

# Get disk
get_disk(){
    disk_array_card=$(lspci -v | grep -i lsi | head -n1 | awk -F"[:/]" '{print$NF}')
    disk_total=$(lsblk  -b | egrep "^s|^v|^n" | awk '{sum+= $4} END{print int(sum/1024/1024/1024)"G"}')
    disk_physics=$(lsblk | egrep "^s|^v|^n" | awk '{print$4}' | sort  | uniq  -c | sed -e 's/^[ ]*//g' -e s/[[:space:]]/*/g | tr '\n' '+' | sed s/+$//g)
    disk_sys_drive=$(mount | grep "\/boot" | awk -F"[/ ]" '{print$3}' | sed s#[0-9]##g)
    disk_sys_drive_capacity=$(lsblk | grep "^${disk_sys_drive}" | awk '{print$4}')
    
    # Get disk solt
    if [ $(echo ${disk_array_card} | grep -Ec "3008|2008") -ne 0 ] && [ $( echo ${disk_array_card} | grep -ci "MegaRAID" ) -ne 0 ];then
        if [ ! -e /opt/MegaRAID/MegaCli/MegaCli64 ];then
            install_megacli64
        fi 
        /opt/MegaRAID/MegaCli/MegaCli64 -PDList -aALL | grep -E "Slot|Enclosure position|Inquiry" | sed 'N;N;s/\n/ /g' > ${WORKDIR}/slot.summ
 
    elif [ $(echo ${disk_array_card} | grep -Ec "2308|3008") -ne 0 ];then
        if [ ! -e /usr/local/bin/sas2ircu ];then
            wget -O /opt/sas2ircu http://wx:WXxunlei123$%^@${download_server}:9090/other/tool/disk_tool/sas2ircu &>/dev/null
            chmod +x  /opt/sas2ircu
            ln -sn  /opt/sas2ircu /usr/local/bin/sas2ircu
        fi
    
        /usr/local/bin/sas2ircu 0 display | grep -A 12 "^Device is a Hard disk" | while read  line;do
            if [ $(echo $line | grep -c "^--")  -ne 0 ];then
                let step++
                #touch ${WORKDIR}/sas2ircu.log
                logfile=$(echo "${WORKDIR}/sas2ircu.log${step}")
                echo $line >> ${logfile}
            fi
            echo $line >> ${logfile}
        done
        
        touch ${WORKDIR}/slot.summ
        cd ${WORKDIR}
        for i in $(ls ${WORKDIR} | sed "s:^:`pwd`/:" | grep "sas2ircu.log");do
            cat $i | grep -E "^Enclosure|^Slot|^Serial No" | awk '{printf"%s ",$0}' >> ${WORKDIR}/slot.summ
            echo " " >> ${WORKDIR}/slot.summ
        done
    fi

    echo -e "Disk: \t\tArray card / ${disk_array_card:-'N/A'}"
    echo -e "Disk: \t\tSummary / total capacity:${disk_total:-"N/A"} / Number of Physics:\033[1;32m${disk_physics:-"N/A"}\033[0m / System disk:${disk_sys_drive:-"N/A"} ${disk_sys_drive_capacity:-"N/A"}"
 
    disks=$(lsblk | grep disk|awk '{print $1}'|sort)
    for n in $disks;do
        size=$(lsblk | grep disk|grep $n |awk '{print $4}'|sort)
        disk_model=$(hdparm -I /dev/$n 2>/dev/null | grep -i "Model Number"|awk '{print $3,$4}')
        disk_sn=$(hdparm -I /dev/$n 2>/dev/null | grep -i "Serial Number"|awk '{print $3}')
        disk_slot=$(cat ${WORKDIR}/slot.summ 2>/dev/null | grep ${disk_sn} 2>/dev/null|  awk '{for (i=1;i<=(NF-4);i++)printf("%s ", $i);print ""}'| sed -e s/'Inquiry Data:'//g -e s/'Inquiry'//g)
	echo -e "Disk: \t\tid:${n:-"N/A"} size:${size:-"N/A"} model:${disk_model:-"N/A"} sn:${disk_sn:-"N/A"}" location:${disk_slot:-"N/A"}
    done

}    

# Get network 
get_nic(){
    [ $(ps auxf | grep  -c [l]ldpad) -lt 1 ] && lldpad -d &>/dev/null
    lshw -short > ${WORKDIR}/lshw_short.log
    cat /proc/net/dev | grep -v "tun\|face\|lo\|Inter\|ppp\|docker\|galaxy\|virbr\|macvlan\|kube\|dummy" | awk -F":" '{print$1}' | sed s/[[:space:]]//g | sort >${WORKDIR}/eth_list.log

    while read line;do
        eth_mac=$(ethtool -P $line|awk '{print $NF}')
        eth_port=$(ethtool $line | grep "Supported ports" | awk -F ":" '{print$2}'| sed s/[[:space:]]//g)
        eth_max_speed=$(ethtool $line |grep base|tail -1|grep -Eo "[0-9]+")
        eth_speed=$(ethtool $line | grep "Speed" | awk  -F":" '{print$2}'|sed s/[[:space:]]//g)
        eth_link=$(ethtool $line | grep "Link detected" | awk -F":" '{print$2}'| sed s/[[:space:]]//g)
        eth_ip=$(ip ad show dev $line |grep -v inet6 | grep inet|awk '{print $2}')
        eth_gw=$(route -n | grep -w $line$ | awk '{print$2}' | grep -v '0.0.0.0')
        ethtool -l  $line &>/dev/null
        if [ $? -eq 0 ];then
            eth_max_combined=$(ethtool -l  $line |  grep Combined |  head -n1 |awk -F":" '{print$2}'|sed s/[[:space:]]//g 2>/dev/null)
            eth_cur_combined=$(ethtool -l  $line |  grep Combined |  tail -n1 |awk -F":" '{print$2}' |sed s/[[:space:]]//g 2>/dev/null)
        fi
        eth_physics=$(grep -w $line ${WORKDIR}/lshw_short.log | awk '{$1=$2=$3="";print}' | head -n 1| sed 's/^[ ]*//g' )
        if [ $(ifconfig  $line | grep  "^${line}" | grep -c UP) -ne 0  ];then
           if [ $(echo $line | grep  -Ec "^eth|^em|^p[0-9]|^en." ) -ne 0 ];then
               lldptool  set-lldp -i $line adminStatus=rxtx  &>/dev/null   
               lldptool  -T -i $line -V  sysName enableTx=yes  &>/dev/null
               lldptool  -T -i $line -V  portDesc enableTx=yes &>/dev/null
               lldptool  -T -i $line -V  sysDesc enableTx=yes  &>/dev/null
               eth_ifname=$(lldptool -t -n -i $line | grep -E "Ifname" | awk -F ":" '{print$2}')
           fi
        fi 
        echo -e  "Network: \t${line:-N/A} / port type:${eth_port:-N/A} mac:${eth_mac:-N/A} physics_max_speed:${eth_max_speed:-N/A }Mb/s speed:${eth_speed:-N/A} link:${eth_link:-N/A} / max combined:${eth_max_combined:-N/A} / cur combined:${eth_cur_combined:-N/A} physics:${eth_physics:-N/A} IP:${eth_ip:-N/A} GW:${eth_gw:-N/A} Ifname:${eth_ifname:-N/A}"
    done<${WORKDIR}/eth_list.log
}

# Get ipmi info
get_ipmi(){
    ipmitool sdr > /${WORKDIR}/ipmi_info.txt
    
    cat /${WORKDIR}/ipmi_info.txt | grep -E "FAN|Fan" | grep -v Watts | grep -v ns | grep -v "0x00" | awk -F '|' '{print$1,$2}' > /${WORKDIR}/ipmi_info_FAN.txt
    cat /${WORKDIR}/ipmi_info.txt | grep -E "Temp|degrees" | grep -v ns |  awk -F '|' '{print$1,$2}' > /${WORKDIR}/ipmi_info_Temp.txt
    cat /${WORKDIR}/ipmi_info.txt | grep Watts | grep -v ns |  awk -F '|' '{print$1,$2}' > /${WORKDIR}/ipmi_info_Watts.txt
    
    while read line;do
        echo -e "FAN: \t\t${line:-N/A}"
    done</${WORKDIR}/ipmi_info_FAN.txt

    while read line;do
        echo -e "Temp: \t\t${line:-N/A}"
    done</${WORKDIR}/ipmi_info_Temp.txt

    while read line;do
        echo -e "Watts: \t\t${line:-N/A}"
    done</${WORKDIR}/ipmi_info_Watts.txt
}

# main  
main(){
  basic_env_setup
  basic_install_pack
  get_summary
  get_cpu
  get_mem
  get_disk
  get_nic
  get_ipmi
}

# Determine the operating system
if [ -e /etc/redhat-release ];then
    # centos
    os_type=0
elif [ -e /etc/debian_version ];then
    # debian
    os_type=1
fi

# Script entry
main
