#!/bin/sh
# Ported from Slackware .build

# Set initial variables:
PKGNAM=aalib
VERSION=${VERSION:-1.4rc5} # We can use a release candidate for this lib because it's not all that mission-critial anyway.
AALIB_VERSION=${AALIB_VERSION:-1.4.0}
ARCH=${ARCH:-x86_64}
BUILD=${BUILD:-2}

CWD=`pwd`
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-${PKGNAM}
rm -rf $PKG
mkdir -p $PKG

if [ "$ARCH" = "i386" ]; then
  SLKCFLAGS="-O2 -march=i386 -mcpu=i686"
elif [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mcpu=i686"
elif [ "$ARCH" = "s390" ]; then
  SLKCFLAGS="-O2"
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  SLKLDFLAGS="-L/usr/lib64"
fi

cd /tmp
tar xzvf $CWD/$PKGNAM-$VERSION.tar.gz
cd ${PKGNAM}-${AALIB_VERSION}

if [ $ARCH = "x86_64" ]; then
  zcat $CWD/$PKGNAM-x86_64.diff.gz | patch -p1 --verbose || exit 1
fi

# Make sure ownerships and permissions are sane:
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 {} \;

# Configure:
LDFLAGS="$SLKLDFLAGS" \
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=/usr \
  --libdir=/usr/lib64 \
  --sysconfdir=/etc \
  $ARCH-slackware-linux

# Build and install:
make || exit 1
make install DESTDIR=$PKG || exit 1

# Strip binaries:
( 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
)

# Install documentation:
mkdir -p $PKG/usr/doc/$PKGNAM-$VERSION
cp -a \
  ANNOUNCE AUTHORS COPYING ChangeLog INSTALL NEWS README README.OS2 \
  $PKG/usr/doc/$PKGNAM-$VERSION

# Compress and link manpages, if any:
if [ -d $PKG/usr/man ]; then
  ( cd $PKG/usr/man
    for manpagedir in $(find . -type d -name "man*") ; do
      ( cd $manpagedir
        for eachpage in $( find . -type l -maxdepth 1) ; do
          ln -s $( readlink $eachpage ).gz $eachpage.gz
          rm $eachpage
        done
        gzip -9 *.?
      )
    done
  )
fi

# Compress info files, if any:
if [ -d $PKG/usr/info ]; then
  ( cd $PKG/usr/info
    rm -f dir
    gzip -9 *
  )
fi

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cd $PKG
makepkg -l y -c n ../$PKGNAM-$VERSION-$ARCH-$BUILD.tgz

# Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
  rm -rf /tmp/$PKGNAM-$AALIB_VERSION
  rm -rf $PKG
fi