#!/usr/bin/env bash
TOOL_NAME="Intel GPU Information Tool"
TOOL_VER="0.3"

[[ "$1" != "nocolor" ]] && source colors

echo "${CYAN}${TOOL_NAME} v${TOOL_VER}${NOCOLOR}"

if [[ "$1" == -h || "$1" == --help ]]; then
	echo "Usage: intel-info [index] [busid:00] ..."
	exit 0
fi


HIGH_TEMP=100
MID_TEMP=70

TIMEOUT_T1=5
TIMEOUT_T2=10
TIMEOUT_T3=15

LEGACY=0

if [[ ! -f $GPU_DETECT_JSON ]]; then
	gpu_detect_json=`gpu-detect listjson`
else
	gpu_detect_json=$(< $GPU_DETECT_JSON)
fi


idx=0
while IFS=";" read busid brand name mem vbios memtype uuid; do
	BUSID[$idx]="$busid"
	BRAND[$idx]="$brand"
	NAME[$idx]="$name"
	RAM[$idx]="$mem"
	VBIOS[$idx]="$vbios"
	MEMTYPE[$idx]="$memtype"
	UUID[$idx]="$uuid"
	((idx++))
done < <( echo "$gpu_detect_json" | jq -r -c '.[] | select(.brand == "intel" or .vendor == "INTEL") | (.busid+";"+.brand+";"+.name+";"+.mem+";"+.vbios+";"+.mem_type+";"+.uuid)' 2>/dev/null )

ubuntu_ver=$(lsb_release -rs | tr -d '.')
intel_mod_version=$(modinfo i915 | grep -E "^version" | awk '{print $2}' || uname -r -v | sed 's/\.hiveos.*//' | sed 's/0-hiveos #//')
intel_ocl_version=$(dpkg-query --showformat='${Version}' --show intel-opencl-icd  2>/dev/null)

if [[ $ubuntu_ver -ge 2004 && -n $intel_ocl_version ]]; then
    echo -n "Module version: ${GREEN}$intel_mod_version${NOCOLOR} "
    echo    "OpenCL version: ${GREEN}$intel_ocl_version${NOCOLOR}"
else
    echo "${YELLOW}Not suitable Image or Intel OCL not installed${NOCOLOR}"
    exit 1
fi

n=${#BUSID[@]}
if [[ $n -eq 0 ]]; then
	echo  "${RED}No Intel GPU detected${NOCOLOR}"
	exit 1
fi

index=-1
echo; date
for (( i=0; i < $n; i++ )); do
	gpu_idx=
	if [[ "${BRAND[$i]}" == "intel" ]]; then
		((index++))
		gpu_idx=$index
	fi
	busid="${BUSID[$i]}"
        
	# filter output by index or busid
	[[ ! -z "$@" && ! " $@ " =~ ( ${gpu_idx:--} ) && ! " $@ " =~  ( ${busid/.0} ) ]] && continue

	echo ""
	if [[ "${BRAND[$i]}" != "intel" ]]; then
		echo "${YELLOW}===${NOCOLOR} GPU ${CYAN}-${NOCOLOR}, ${PURPLE}$busid ${RED}${NAME[$i]}${NOCOLOR} - ${BYELLOW}${VBIOS[$i]} ${YELLOW}===${NOCOLOR}"
		continue
	fi

	[[ `echo /sys/bus/pci/devices/0000:$busid/drm/card*/` =~ \/card([0-9]+)\/ ]]
	cardno=${BASH_REMATCH[1]}

	echo "${YELLOW}===${NOCOLOR} GPU ${CYAN}$index${NOCOLOR}, ${PURPLE}$busid ${CYAN}${NAME[$i]} ${WHITE}${RAM[$i]} ${YELLOW}===${NOCOLOR}"

	[[ -z $cardno ]] && echo "${RED}ERROR: can not match card id${NOCOLOR}" && continue

	hwmondir=`realpath /sys/class/drm/card$cardno/device/hwmon/hwmon*/`

        [[ -e /hive/sbin/igsc && -n $mei_id ]] && vbios_fw=`/hive/sbin/igsc fw version -d /dev/$mei_id 2>/dev/null| awk '{print $4}'` || vbios_fw=
        echo "1" > /sys/class/drm/card$cardno/device/rom && vbios_oprom=`xxd  -seek 0x08a0 -l 32 -ps /sys/class/drm/card$cardno/device/rom |sed 's/2020//g' | xxd -r -p | tr -d '\0'`
        [[ -n $vbios_fw ]] && vbios="$vbios_fw($vbios_oprom)" || vbios="$vbios_oprom"

	echo -n "  VBIOS: ${WHITE}${vbios}${NOCOLOR}"
	echo ""

        gpu_stat=$(gpu-stats)
        pwr_idx=$(echo $gpu_stat | jq --arg busid $busid '.busids | index($busid)')
        pwr=$(echo $gpu_stat | jq -r --arg idx $pwr_idx '.power[$idx|tonumber]')

        core_mhz=$(cat /sys/class/drm/card${cardno}/gt_act_freq_mhz)
        [[ $core_mhz -eq 0 ]] && core_mhz=$(cat /sys/class/drm/card${cardno}/gt_cur_freq_mhz)
        core_max_mhz=$(cat /sys/class/drm/card${cardno}/gt_RP0_freq_mhz)
        pl_raw=$(cat $hwmondir/power1_max)
        [[ -n $pl_raw && $pl_raw -gt 0 ]] && pl=$((pl_raw/1000000)) || pl=
        vddc=$(cat $hwmondir/in0_input)
	echo -n "  Core: ${WHITE}${core_mhz} MHz${NOCOLOR}"
	[[ -n $vddc && $vddc -gt 0 ]] && echo -n " ${WHITE}${vddc}mV${NOCOLOR}"
        [[ -n $core_max_mhz ]] && echo -n "  Max Core: ${WHITE}${core_max_mhz} MHz${NOCOLOR}"
        [[ -n $pwr ]] && echo -n "  PWR: ${WHITE}${pwr} W${NOCOLOR}"
        [[ -n $pl ]]  && echo -n "  PWR Limit: ${WHITE}${pl} W${NOCOLOR}"
	echo ""
        
        if [[ -e ${hwmondir}/temp1_input ]]; then 
            temp=$(timeout --foreground -s9 2 head -1 ${hwmondir}/temp1_input)
            temp=$(( temp / 1000 ))
            if [[ $temp -le 55 ]]; then
                color=$GREEN
            elif [[ $temp -le 70 ]]; then
                color=$YELLOW
            else
                color=$RED
            fi
            echo -n "  GPU Temp: ${color}${temp} C${NOCOLOR}"
        fi
        if [[ -e ${hwmondir}/fan1_input ]]; then
            fan_rpm=$(( $(timeout --foreground -s9 2 head -1 ${hwmondir}/fan1_input) ))
            fan_speed=$(( $fan_rpm * 100 / 1800 )) # A770 & A750 uses 1800 rpm fans
            [[ $fan_speed -gt 100 ]] && fan_speed=100
            echo -n "  FAN: ${WHITE}$fan_speed%${NOCOLOR} RPM: ${WHITE}${fan_rpm}${NOCOLOR}"
        fi
	echo ""

	if [[ -f /sys/class/drm/card${cardno}/device/current_link_speed ]]; then
		pciespeed=`cat /sys/class/drm/card$cardno/device/current_link_speed`
		pciewidth=`cat /sys/class/drm/card$cardno/device/current_link_width`
		echo  "  PCIE Link speed: ${WHITE}${pciespeed:-n/a}${NOCOLOR}, PCIE Link width: ${WHITE}${pciewidth:-n/a}${NOCOLOR}"
	fi

	echo "  Memory ${meminfo}type: ${WHITE}${MEMTYPE[$i]}${NOCOLOR}"
done
echo