#!/bin/sh
# Heavily based on the Slackware 12.0 SlackBuild
# http://shapelib.maptools.org/

CWD=`pwd`
NAME=shapelib
VERSION=1.2.10
TARGET=i486
BUILD=1lu
ARCH=${ARCH:-i486}

SOURCE=http://dl.maptools.org/dl/shapelib/$NAME-$VERSION.tar.gz
wget -c $SOURCE

if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-$NAME

if [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mtune=i686"
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2"
  elif ["$ARCH" = "athlon" ]; then
  SLKCFLAGS="-O3 -march=athlon-xp -pipe -fomit-frame-pointer"
fi

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
if [ ! -d $PKG ]; then
  mkdir -p $PKG # place for the package to be built
fi

echo "+==============+"
echo "| $NAME-$VERSION |"
echo "+==============+"

cd $TMP
tar xzvf $CWD/$NAME-$VERSION.tar.gz
cd $NAME-$VERSION
zcat $CWD/shpgeo.diff.gz | patch -p1 -E --backup --verbose
chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;

CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
make
cd contrib
make
cd ..
make lib

mkdir -p $PKG/usr/bin
mkdir -p $PKG/usr/lib
mkdir -p $PKG/usr/include/libshp

for file in `find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d :`;
do
 cp $file $PKG/usr/bin
 done

 for file in `find contrib/ | xargs file | grep "executable" | grep ELF | cut -f 1 -d :`;
do
 cp $file $PKG/usr/bin
 done

for lib in `find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d :`;
do
 cp $lib $PKG/usr/lib
 done

cp -a .libs/* $PKG/usr/lib
cp shapefil.h $PKG/usr/include/libshp

chmod 755 $PKG/usr/bin/*

mkdir -p $PKG/usr/doc/$NAME-$VERSION
cp -a ChangeLog LICENSE.LGPL README $PKG/usr/doc/$NAME-$VERSION
chown -R root:root $PKG/usr/doc/$NAME-$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
)

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/slack-desc > $PKG/usr/doc/$NAME-$VERSION/slack-desc
cat $CWD/$NAME.SlackBuild > $PKG/usr/doc/$NAME-$VERSION/$NAME.SlackBuild
cd $PKG
requiredbuilder -v -y -s $CWD $PKG
makepkg -l y -c n $CWD/$NAME-$VERSION-$ARCH-$BUILD.tgz

if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/$NAME-$VERSION
  rm -rf $PKG
fi
