#! /bin/sh
#
# extramodules  Install extra kernel modules from block device.
#
# Version:      @(#)extradebs  1.0  6-Mar-2007  jojeda@emergya.es
#

set -e 

 
exec > /target/var/log/ubiquity_hooks.log 2>&1 

set -x

modules_dir="/mnt/extrahooks/modules/"
modules_file="/mnt/extrahooks/modules/modules.conf"
target_file="/target/etc/initramfs-tools/modules"
target_dir="/target/lib/modules/$(uname -r)/misc/"

is_valid_dir () {
  [ -e "/mnt/extrahooks/.version" ] || return 1
  return 0
}

get_fstype () {
/lib/udev/vol_id -t $1 || true
}

# Checking for block devices
if [ ! -d /mnt ]; then
  mkdir /mnt
fi
for dev in $(echo /dev/[sh]d[a-z]*)
  do
  fs=""
  fs=$(get_fstype $dev)
  case $fs in
    ""|swap|unknown)
          continue ;;
  esac

  if  ! $(mount -r -t $fs $dev /mnt/) ; then
    continue
  elif ( ! is_valid_dir );then
    umount /mnt
    continue
  fi

  # Install modules to the target system
  if [ ! -d "$target_dir" ]; then
    mkdir -p $target_dir
  fi
  cp $modules_dir/*.ko $target_dir/
  chroot /target depmod -a $(uname -r)
  
  if [ -f "$modules_file" ]; then
    grep -v "^#" $modules_file >> $target_file
  fi

  sleep 2
  umount /mnt 
done

exit 0
