#!/bin/sh
# Collecting hardware/firmware information
# http://www.acm.uiuc.edu/sigops/roll_your_own/7.c.1.html

if [ "$(id -u)" != 0 ]; then
    sudo sh $(readlink -m $0) $*
    exit
fi

export LANG=C
export LC_ALL=C

build_stamp ()
{
    printf "=== Build Stamp ===\n\n"
    cat /etc/buildstamp
    printf "\n"
}

cpu_id ()
{
    printf "=== CPU ===\n\n"
    cpuid
    printf "\n"
}

dmi_info ()
{
    printf "=== DMI ===\n\n"
    dmidecode
    printf "\n"
}

edid_info ()
{
    printf "=== EDID ===\n\n"
    timeout=50  # polling for 5 sec
    output=$(mktemp)

    get-edid > $output &
    pid=$!

    while [ $timeout -gt 0 ]
    do
        ps $pid > /dev/null 2>&0
        [ $? -eq 0 ]; break
        timeout=$((timeout-1))
        sleep .1
    done

    if [ $timeout -eq 0 ]; then
        printf "[ERROR] get-edid failed\n"
        cat $output
        kill -9 $pid
    else
        parse-edid < $output
    fi

    printf "\n"
}

disk_info ()
{
    printf "=== DISK ===\n\n"
    df -h
    fdisk -l
    lsblk --nodeps -a /dev/sd*
    for i in /dev/sd?; do
	hdparm -i $i
    done
    printf "\n"
    for i in $(fdisk -l 2>/dev/null | grep Linux$ | awk '{print $1}'); do
	printf "=== PART $i ===\n\n"
	tune2fs -l $i
	printf "\n"
    done
}

audio_info ()
{
    printf "=== AUDIO ===\n\n"
    amixer
    printf "\n"
}

find_hardware_by_class ()
{
    printf "=== $2 ===\n\n"
    for i in $(lspci -n | awk "{ if (\$2 ~ /$1/) print \$1; }"); do
        local dir=$(find /sys/devices -type d -name *$i)
        local vendor=$(cat $dir/vendor)
        local device=$(cat $dir/device)
        lspci -vvnn -d $vendor:$device
    done
    printf "\n"
}

dump_device_list()
{
    printf "\n=== lspci ===\n"
    lspci -vvnn
    printf "\n=== lsusb ===\n"
    lsusb -v
    printf "\n=== lshw ===\n"
    lshw
    printf "\n"
}

build_stamp
cpu_id
dmi_info
edid_info
disk_info
dump_device_list
find_hardware_by_class '^02' 'Network Controllers'
find_hardware_by_class '^03' 'Display Controllers'
find_hardware_by_class '^04' 'Multimedia Devices'
audio_info
for i in /proc/asound/card*/codec#*; do
    printf "=== $i ===\n\n"
    cat $i
    printf "\n"
done

printf "=== DMESG ===\n\n"
dmesg
printf "\n"

#EFI mode show current efibootmgr status
if [ -e /sys/firmware/efi ]; then
    efibootmgr -v
fi

printf "=== SCRIPTS ===\n\n"
