#!/bin/sh

# Slackware build script for cfitsio

# Written by Andre Barboza <bmg.andre@gmail.com>

# Exit on most errors
set -e

PRGNAM=cfitsio
VERSION=3.060
ARCH=${ARCH:-i486}	# this should not change
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}	# the "_SBo" is required
CWD=$(pwd)
TMP=${TMP:-/tmp/SBo}	# For consistency's sake, use this
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}	# Drop the package in /tmp
TARGET=${TARGET:-i486}

if [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mtune=i686"
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
fi

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM
tar xvf $CWD/$PRGNAM`echo $VERSION|sed "s/\.//g"`.tar.gz
cd $PRGNAM
chown -R root:root .
find . \
 \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
 -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
 -exec chmod 644 {} \;

CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=$PKG/usr \
  --sysconfdir=$PKG/etc \
  --localstatedir=$PKG/var \
  --mandir=$PKG/usr/man \
  --build=$TARGET-slackware-linux

# Compile the application and install it into the $PKG directory
make
make install

( cd $PKG/usr/lib/pkgconfig
  PKGCONFIG=`echo $PKG|sed 's/\//\\\ \//g'|sed 's/\ //g'`
  cat cfitsio.pc | sed "s/$PKGCONFIG//g" > cfitsio.pc
)

# Strip binaries and libraries - this can be done with 'make install-strip'
# in many source trees, and that's usually acceptable if so, but if not, 
# use this:
( 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
)

# Copy program documentation into the package
# Also, include the SlackBuild script in the documentation directory
mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a README  README.MacOS  README.win32 License.txt $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

# Copy the slack-desc (and a custom doinst.sh if necessary) into ./install
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

# Make the package; be sure to leave it in $OUTPUT
cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.tgz

