#!/bin/sh
# Set initial variables:
CWD=`pwd`
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-ncompress

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

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
rm -rf $PKG
mkdir -p $PKG

cd $TMP
rm -rf ncompress-${VERSION}
tar xzf $CWD/ncompress-${VERSION}.tar.gz
cd ncompress-${VERSION}
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 {} \;

zcat $CWD/ncompress.make.diff.gz | patch -p1 --verbose || exit 1
zcat $CWD/ncompress.lfs2.diff.gz | patch -p1 --verbose || exit 1
zcat $CWD/ncompress.filenamelen.diff.gz | patch -p1 --verbose || exit 1
zcat $CWD/ncompress.2GB.diff.gz | patch -p1 --verbose || exit 1
zcat $CWD/ncompress.zerobyteforce.diff.gz | patch -p1 --verbose || exit 1
zcat $CWD/ncompress-${VERSION}-bssUnderflow.patch.gz | patch -p1 --verbose || exit 1
zcat $CWD/ncompress-${VERSION}-endians.patch.gz | patch -p1 --verbose || exit 1

make ENDIAN=4321 || exit 1
mkdir -p $PKG/usr/bin
cat compress > $PKG/usr/bin/compress
chmod 755 $PKG/usr/bin/compress
( cd $PKG/usr/bin ; ln -sf compress uncompress )
mkdir $PKG/bin
( cd $PKG/bin ; ln -sf /usr/bin/compress compress )
( cd $PKG/bin ; ln -sf compress uncompress )
mkdir -p $PKG/usr/man/man1
cat compress.1 | gzip -9c > $PKG/usr/man/man1/compress.1.gz
echo '.so man1/compress.1' | gzip -9c > $PKG/usr/man/man1/uncompress.1.gz
mkdir -p $PKG/usr/doc/ncompress-${VERSION}
cp -a \
  Acknowleds LZW.INFO README \
  $PKG/usr/doc/ncompress-${VERSION}

# Strip everything for good measure:
( 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/install
cat $CWD/slack-desc > $PKG/install/slack-desc

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