#!/bin/sh

# Note that this script is not only /sbin/lrm-manager, but it also
# ends up being the postinst for nic-restricted-modules.  Take care
# when adding features to make sure they'll work in d-i's busybox

set -e

KVER="$(uname -r)"
DEPMOD=yes

if [ "$1" = "--quick" ]; then
  DEPMOD=no
fi

# check if we have the kernel objects

if [ ! -d /lib/linux-restricted-modules/"$KVER" ]; then
  exit 0
fi

# if tmpfs is already mounted, skip it.
# NOTE that at this point in time we have no /proc or other fancy things to check

if [ ! -f /lib/modules/"$KVER"/volatile/.mounted ]; then
  mkdir -p /lib/modules/"$KVER"/volatile/
  mount -t tmpfs -o mode=0755 tmpfs /lib/modules/"$KVER"/volatile/
  touch /lib/modules/"$KVER"/volatile/.mounted
fi

cd /lib/linux-restricted-modules/"$KVER"
for module in *; do
    ld_static -r -o /lib/modules/"$KVER"/volatile/$module.ko $module/* || true
    touch --date="1 day" /lib/modules/"$KVER"/volatile/* 2>/dev/null || true
done

if [ "$DEPMOD" = "yes" ]; then
  depmod -Aq
fi

exit 0
