#!/bin/sh
CWD=`pwd`
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-curl

VERSION=7.15.5
ARCH=${ARCH:-i486}
BUILD=${BUILD:-3_slack11.0}

# Uncomment to build a no-SSL version:
#SSLOPT=--without-ssl

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

rm -rf $PKG
mkdir -p $PKG
cd $TMP
rm -rf curl-$VERSION
tar xjvf $CWD/curl-$VERSION.tar.bz2
cd curl-$VERSION

zcat $CWD/curl-7.15.5-CVE-2009-0037.patch.gz | patch -p1 --verbose || exit 1
zcat $CWD/curl-7.15.5-CVE-2009-2417.patch.gz | patch -p0 --verbose || exit 1

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 {} \;

CFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=/usr \
  --mandir=/usr/man \
  $SSLOPT
make -j3 || exit 1
make install DESTDIR=$PKG || exit 1

( 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/libcurl.a

mkdir -p $PKG/usr/doc/curl-$VERSION
cp -a \
  CHANGES COPYING README UPGRADE \
  $PKG/usr/doc/curl-$VERSION
( cd docs
  rm -rf Makefile* curl-config.1 curl-config.html curl.1 curl.html libcurl
  cp -a \
    BUGS CONTRIBUTE FAQ FEATURES INSTALL INTERNALS MANUAL README.win32 RESOURCES THANKS TODO examples \
    $PKG/usr/doc/curl-$VERSION )

# Compress and if needed symlink the man pages:
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

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

cd $PKG
makepkg -l y -c n ../curl-$VERSION-$ARCH-$BUILD.tgz