#!/bin/sh

# The purpose of this script is to produce a list. This list should be a 
# formatted list of hardware on the system that might have firmware to
# download.
#
# For example, a sample list might look like this:
#       system_bios(ven_0x1028_dev_0x0123)
#       system_firmware(ven_0x1028_dev_0x0123)
#       pci_firmware(ven_0x9999_dev_0x1111_subven_0xAAAA_subdev_0xAAAA)
#       pci_firmware(ven_0x9999_dev_0x2222_subven_0xAAAA_subdev_0xBBBB)
#       pci_firmware(ven_0x9999_dev_0x3333_subven_0xAAAA_subdev_0xCCCC)
#       pci_firmware(ven_0x9999_dev_0x4444)
#       pci_firmware(ven_0x9999_dev_0x5555)
#
# This list is then fed to 'yum' or 'up2date' or other package manager to
# find the list of RPM names that "Provide:" these firmware items.
# The system package manager is then invoked to download/install these RPMs.
#

#trim leading and trailing whitespace
trim_string(){
    local str=$1
    while true
    do
        local before=$str
        str=${str%% }
        str=${str## }
        if [ "$str" = "$before" ]; then break; fi
    done
    echo $str
}

# ensure we have permissions to run the inventory. 
test_perms() {
    getSystemId > /dev/null 2>&1
    return $?
}

get_system_id(){
    local id=$(getSystemId | grep 'System ID:' | cut -d: -f2)
    echo $(trim_string $id)
}

is_dell(){
    local id=$(getSystemId | grep 'Is Dell:' | cut -d: -f2)
    echo $(trim_string $id)
}

get_system_bios(){
    id=$(get_system_id)
    if [ $(is_dell) -eq 1 ]; then
        echo "system_bios(ven_0x1028_dev_$id)"         
    fi
}

get_system_firmware(){
    id=$(get_system_id)
    if [ $(is_dell) -eq 1 ]; then
        echo "system_firmware(ven_0x1028_dev_$id)"         
    fi
}

do_get_pci_firmware(){
    line=$1
    vendev=$(echo $line | perl -p -e 's/.*?"[\w ]+"\s"(\w+)"\s"(\w+)"\s.*?"(\w*)"\s"(\w*)"/$1 $2 $3 $4/g;')
    vendor=$(echo $vendev | cut -f1 -d' ')
    device=$(echo $vendev | cut -f2 -d' ')
    subvendor=$(echo $vendev | cut -f3 -d' ')
    subdevice=$(echo $vendev | cut -f4 -d' ')
    echo -n "pci_firmware(ven_0x${vendor}_dev_0x${device}"
    if [ -n "$subvendor" ]; then
        echo -n "_subven_0x${subvendor}_subdev_0x${subdevice}"
    fi
    echo ")"
}

get_pci_firmware(){
    lspci -n -m | 
    while read line
    do
        do_get_pci_firmware "$line"
    done
}

main(){
    if ! test_perms
    then
        echo "Insufficient permissions to inventory system. Try running as root."  1>&2
        exit 1
    fi

    get_system_bios
    get_system_firmware
#    get_pci_firmware
}

main $*

