#!/bin/sh

set -e

# evms.mkinitrd, Matt Zimmerman <mdz@debian.org>
#
# Based in part on information in INSTALL.initrd from the EVMS 2.0.0
# distribution

evmsprogs="/sbin/evms_activate /usr/bin/stat"
evmsplugins=$(echo /lib/evms/*.so)
skip_evmsplugins="csm ext2 ha jfs reiser replace rsct swap xfs"

libdeps() {
    prog="$1"
    ldd "$prog" | sed -e 's/.*=>[[:blank:]]*\([^[:blank:]]*\).*/\1/'
}

install_libs() {
   for lib in $*; do
       #echo "Found dependent library: $lib"
       if [ ! -e "$INITRDDIR/lib/$(basename $lib)" ]; then
           cp -p "$lib" "$INITRDDIR/lib/$(basename $lib)"
       fi
   done
}

evmsroot=$(grep -v '^ *#' /etc/fstab | awk '$2 == "/" && $1 ~ "^/dev/evms/" { print $1 }')
if [ -z "$evmsroot" ]; then
    exit 0
fi

echo
echo "This is an EXPERIMENTAL script for creating an initrd for booting"
echo "with the root filesystem on an EVMS volume.  Please report bugs and"
echo "send feedback using reportbug(1).  This script is not currently"
echo "fully functional.  YOU HAVE BEEN WARNED!"
echo
          
# programs
for prog in $evmsprogs; do
    install_libs $(libdeps "$prog")
    cp -p --parents "$prog" $INITRDDIR
done

# plugins
for plugin in $evmsplugins; do
    plugin_name=$(echo "$plugin" | sed -e 's,.*/\([^-]*\)-.*$,\1,')
    skip=0
    for excluded in $skip_evmsplugins; do
        if [ "$plugin_name" = "$excluded" ]; then
            skip=1
            break
        fi
    done
    if [ $skip -eq 1 ]; then
        #echo "Excluding plugin: $plugin"
        continue
    fi
    install_libs $(libdeps $plugin)
    cp -p --parents "$plugin" $INITRDDIR
done

# evms.conf
cp -p --parents /etc/evms.conf $INITRDDIR

# linuxrc
cp -p /usr/share/evms/linuxrc $INITRDDIR/scripts/evms

# Copy all of drivers/md, since we're not (yet) sure what we'll need
find $MODULEDIR/kernel/drivers/md -name '*.o' -o -name '*.ko' \
    | xargs cp -p --parents --target=$INITRDDIR
