#!/bin/sh
CWD=`pwd`
TMP=${TMP:-/tmp}
PKG=$TMP/package-dmapi

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

if [ ! -d $TMP ]; then
  mkdir -p $TMP
fi
rm -rf $PKG
mkdir -p $PKG

cd $TMP
rm -rf dmapi-$(echo $VERSION | cut -f 1 -d '-')
tar xzvf $CWD/dmapi_$VERSION.tar.gz
cd dmapi-$(echo $VERSION | cut -f 1 -d '-')

chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;
find . -perm 600 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;
find . -perm 400 -exec chmod 644 {} \;
find . -perm 440 -exec chmod 644 {} \;
find . -perm 777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 511 -exec chmod 755 {} \;
find . -perm 711 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;

# Add DESTDIR support and improve docs install location:
zcat $CWD/dmapi.destdir.diff.gz | patch -p1 --verbose --backup --suffix=.orig || exit 1

# Make sure you have the same version of autoconf as the
# developers did...  ;-)
autoconf

./configure \
  --prefix=/ \
  --exec-prefix=/ \
  --sbindir=/bin \
  --bindir=/usr/bin \
  --libdir=/lib \
  --libexecdir=/usr/lib \
  --includedir=/usr/include \
  --mandir=/usr/man \
  --datadir=/usr/share

make || exit 1
make install DESTDIR=$PKG
make install-dev DESTDIR=$PKG
make install-lib DESTDIR=$PKG

mv $PKG/usr/share/doc $PKG/usr
( cd $PKG/usr/doc ; mv dmapi dmapi-$VERSION )
# It would be nice to keep the same timestamps that the files have in the source:
rm -rf $PKG/usr/doc/dmapi-$VERSION/ea-conv
cp -a \
  README doc/COPYING doc/PORTING doc/ea-conv \
  $PKG/usr/doc/dmapi-$VERSION

( 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
)
strip -g $PKG/usr/lib/*.a

# Remove bogus files:
rm -f $PKG/lib/*.a $PKG/lib/libdm.so $PKG/lib/*.la $PKG/usr/lib/*.la
# Make /usr/lib/libdm.so a symlink to /lib:
if [ -f $PKG/lib/libdm.so.0 ]; then
  ( cd $PKG/usr/lib ; rm -f libdm.so ; ln -sf /lib/libdm.so.0 libdm.so )
else
  exit 1
  # and fix yer script!!!
fi
# Fix shared library perms:
chmod 755 $PKG/lib/*

# Gzip the man pages:
( cd $PKG/usr/man
  for i in `find . -type l` ; do ln -s $( readlink $i ).gz $i.gz ; rm $i ; done
  gzip -9 */*.?
)

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

cd $PKG
makepkg -l y -c n $TMP/dmapi-$(echo $VERSION | tr - _ )-$ARCH-$BUILD.tgz