#!/usr/bin/bash
# script to find the modules required for a specific block device
# Copyright (C) 2014 McAfee, Inc. All rights reserved.

#p1=block device

# find the block device for the partition - e.g. 
d=${1##*/}
b=/sys/block/$d
[[ -e $b && -b /dev/$d ]] || { echo "Failed to find partition device $b" >&2 ; exit 1 ; }

# find the full location of the device entry
b=$(readlink -e $b)
[[ -e $b ]] || { echo "Failed to find parent device node" >&2 ; exit 1 ; }

# awk script to determine the modules required from an initial set
# the dependences comes from /proc/modules
# the initial set comes via stdin in reverse order - should be second file
a='
BEGIN{
    debug=0
}
# a module which is present to satisfy some dependencies
(FILENAME!="-") && ($4 != "-") {
    for(i=split($4,n,",");i>0;--i) {
        if (n[i] == "") { continue }
        depends[n[i]]=depends[n[i]] " " $1
        if (debug) { printf "Module %s depends on %s\n",n[i],$1 >"/dev/stderr"}
    }
}
# done with /proc/modules
(FILENAME!="-") {
    next
}
# this is a module which we are required to load
(FILENAME="-") {
    requires[FNR]=$0
    if (debug) { printf "Module %d %s is required\n",FNR,$1 >"/dev/stderr"}
}
# print the modules that this depends on, followed by this module
function traverse_depends(m,i,d) {
    if (debug) { printf "Traverse %s %s\n",m,depends[m] >"/dev/stderr"}
    if (m in done) { return }
    for(i=split(depends[m],d," ");i>0;--i) {
        traverse_depends(d[i])
    }
    printf "%s ",m
    done[m]=1
}
END{
    for(i=FNR;i>0;--i) {
        if (debug) { printf "Module %d is %s\n",i,requires[i] >"/dev/stderr"}
        traverse_depends(requires[i])
    }
}
'

b=$b/device
# find the devices involved in each level of the heirarchy
# the awk at the end reverses the module load order
while [[ $b ]] ; do
    d=$b/driver
    : d $d $(readlink -e $d | sed -e 's,.*/,,')
    # see if the device links to something
    if [[ -e $d ]] ; then
        m=$d/module
        : m $m $(readlink -e $m | sed -e 's,.*/,,')
        # see if the module links to something
        if [[ -e $m ]] ; then
            ls -l $m | sed -e 's,.*/,,'
            # don't need to load the driver, so prefix with #
            #ls -l $d | sed -e 's,.*/,,' -e 's,^,#,'
        else
            # there is a driver but no explicit module, see if there is a module of name
            # ${driver}_mod - since some critical modules don't register their module
            m="$(readlink -e $d | sed -e 's,.*/,,')_mod"
            [[ -e /sys/module/$m ]] && echo $m
        fi
    fi

    # move up a level in the device heirarchy
    b=${b%/*}
done | awk "$a" /proc/modules -
