#!/bin/sh

#     DESCRIPTION
#
# Copy modules to some directory


#     REQUIRES
#
# Define outdir
# Modules list at `/modules'


#     INFO
#
# In future this modules will be loaded inside initrd

NAME="initrd-modules"

verbose()
{
    if [ -n "$GLOBAL_VERBOSE" ]; then
        echo "HOOK: $NAME: $@"
    fi
}

list="/.mkimage/initrd-modules"
outdir="/.mkimage/initrd"

verbose "has started"

if ! [ -r "$list" ]; then
    verbose "Can't locate $list file"
    exit
fi

kernel="$(readlink /boot/vmlinuz)"
ver=${kernel#vmlinuz-}
map="/boot/System.map-$ver"

install_module()
{
    local module=$1 && shift

    [ -z "$module" ] && return

    find /lib/modules/ -regex ".*/$module\.ko$" | while read fpath; do
       verbose "Copy module: $module: $fpath"
       install -D "$fpath" "$outdir/$fpath"

       dep="$(/sbin/modinfo "$fpath" | sed -n -e 's/^depends:[[:space:]]\+//p')"
       [ -z "$dep" ] && continue

       verbose "Module: $(basename $fpath) depends from: $dep"
       echo "$dep," | while read -d ',' mod; do
          install_module $mod
       done
    done
}

if [ -z "$kernel" -o ! -r "$map" ]; then
    verbose "Can't fetch kernel information"
    exit
fi

cat "$list" | while read module; do
  # Remove comments
  module="$(echo "$module" | sed -e 's/^[[:space:]]*//; s/[[:space:]]*$//; s/^#.*//')"
  module="${module%%#*}"
  [ -z "$module" ] && continue
  module="${module%.ko}"
  verbose "Ask to copy $module module"
  install_module "$module"
done

verbose "Create modules dependencies for $ver"
/sbin/depmod -a -F "$map" --basedir "$outdir" "$ver"

verbose "finished"
