#!/bin/sh
# Set initial variables:
CWD=$(pwd)
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-module-init-tools
rm -rf $PKG
mkdir -p $TMP $PKG

VERSION=3.4
ARCH=${ARCH:-i486}
BUILD=${BUILD:-1}

cd $TMP
rm -rf module-init-tools-$VERSION
tar xjf $CWD/module-init-tools-$VERSION.tar.bz2 || exit 1
cd module-init-tools-$VERSION || exit 1
chown -R root:root .
chmod -R a-s,u+w,go+r-w .

# Look for /etc/modprobe.d/ first rather than bailing on the idea if /etc/modprobe.conf
# exists.  IMHO, this is a better default behavior because it allows /etc/modprobe.conf
# to remain behind if something still looks there, and allows a smoother transition 
# towards using /etc/modprobe.d/.
zcat $CWD/modprobe.favor.etc.modprobe.d.diff.gz | patch -p1 --verbose --backup --suffix=.orig || exit 1

CFLAGS= \
./configure \
  --prefix=/ \
  --enable-zlib \
  --build=$ARCH-slackware-linux
make -j4 || exit 1
mkdir -p $PKG/sbin
cat depmod > $PKG/sbin/depmod
cat insmod > $PKG/sbin/insmod
cat insmod.static > $PKG/sbin/insmod.static
cat lsmod > $PKG/sbin/lsmod
cat modinfo > $PKG/sbin/modinfo
cat modprobe > $PKG/sbin/modprobe
cat rmmod > $PKG/sbin/rmmod
chmod 755 $PKG/sbin/*
mkdir -p $PKG/bin
( cd $PKG/bin ; ln -sf /sbin/lsmod . )

mkdir -p $PKG/usr/man/man{5,8}
for file in *.5 ; do
  cat $file | gzip -9c > $PKG/usr/man/man5/$file.gz
done
for file in *.8 ; do
  cat $file | gzip -9c > $PKG/usr/man/man8/$file.gz
done

mkdir -p $PKG/usr/doc/module-init-tools-$VERSION
cp -a AUTHORS CODING COPYING ChangeLog FAQ HACKING INSTALL NEWS README TODO \
  $PKG/usr/doc/module-init-tools-$VERSION

# Strip things:
( cd $PKG
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
)

mkdir -p $PKG/etc
cat << EOF > $PKG/etc/modprobe.conf.new
# /etc/modprobe.conf (old location for Linux 2.6+ config)
#
# The use of this config file is deprecated. 
# Instead, create files in the /etc/modprobe.d/ directory 
# containing modprobe options.
#
# For more information, see "man modprobe.conf".
EOF

mkdir -p $PKG/etc/modprobe.d/

if [ -f $PKG/usr/man/man5/modprobe.conf.5.gz -a ! -e $PKG/usr/man/man5/modprobe.d.5.gz ]; then
  ( cd $PKG/usr/man/man5 ; ln -sf modprobe.conf.5.gz modprobe.d.5.gz )
fi

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
zcat $CWD/doinst.sh.gz > $PKG/install/doinst.sh

# Build the package:
cd $PKG
makepkg -l y -c n $TMP/module-init-tools-$VERSION-$ARCH-$BUILD.tgz

# Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/module-init-tools-$VERSION
  rm -rf $PKG
fi