#!/bin/bash

# Define the command variable
cmd="/opt/hyhal/bin/hy-smi"

# Function to display usage
usage() {
    echo "Usage: $0 [-d device_id]"
    echo "  -d device_id : Get information for specific HCU (integer), default: 0"
    exit 1
}

# Check if hy-smi command is available and working
if ! $cmd >/dev/null 2>&1; then
    echo "no driver online"
    exit 1
fi

# Initialize variables
device_id="0"

# Parse command line options
while getopts "d:h" opt; do
    case $opt in
        d)
            if [[ $OPTARG =~ [0-7] ]]; then
                device_id=$OPTARG
            else
                echo "Error: Device ID must be an integer"
                usage
            fi
            ;;
        h)
            usage
            ;;
        \?)
            usage
            ;;
    esac
done


# Function to get PCI bus number for a specific device
get_pci_bus() {
    local dev_id=$1
    local bus_output
    bus_output=$($cmd --showbus -d $dev_id 2>/dev/null)
    
    # Extract PCI Bus number from the output
    if [[ -n "$bus_output" ]]; then
	pci_bus=$(echo "$bus_output"  --showbus -d 0 | grep 'PCI Bus:' | awk -F ' ' '{print $5}')
    else
        pci_bus="N/A"
    fi
    
    echo "$pci_bus"
}

# Function to parse and format GPU info from hy-smi output
format_gpu_info() {
    local dev_id=$1

    pci_bus=$(get_pci_bus $dev_id)
    
    # Extract values using awk or grep
    model=$($cmd --showproductname -d $device_id | grep  'Card Series' | sed 's/.*Card Series:[[:space:]]*//')
    irq=$(more /sys/bus/pci/devices/$pci_bus/irq)
    hcu_sn=$($cmd --showuniqueid -d $device_id | grep  'Unique ID' | sed 's/.*Unique ID:[[:space:]]*//')
    hcu_uuid=$($cmd --showserial -d $device_id | grep  'Serial Number' | sed 's/.*Serial Number:[[:space:]]*//')
    vbios=$($cmd -v -d $device_id | grep  'VBIOS version' | sed 's/.*VBIOS version:[[:space:]]*//')
    dma_size=$(more  /sys/bus/pci/devices/$pci_bus/dma_mask_bits)
    bus_location=$pci_bus
    gpu_mem=$(more /sys/bus/pci/devices/$pci_bus/mem_info_vram_vendor)
    
    # Format output
    printf "%-15s: %s\n" "Model" "$model"
    printf "%-15s: %s\n" "IRQ" "$irq"
    printf "%-15s: %s\n" "HCU_SN" "$hcu_sn"
    printf "%-15s: %s\n" "HCU_UUID" "$hcu_uuid"
    printf "%-15s: %s\n" "VBIOS" "$vbios"
    printf "%-15s: %s\n" "DMA_Size" "$dma_size"
    printf "%-15s: %s\n" "Bus_Location" "$bus_location"
    printf "%-15s: %s\n" "HCU_Firmware" "$vbios"
    printf "%-15s: %s\n" "HCU_Mem_Vendor" "$gpu_mem"
}


format_gpu_info $device_id
