#!/bin/sh
# Heavily based on the Slackware 13.0 SlackBuild and on crux port of R
# http://clc.morpheus.net/portdb/?command=viewfile&repo=yhafri&port=r&file=Pkgfile
# http://www.r-project.org/

NAME=r-project
VERSION=2.10.1
ARCH=${ARCH:-i486}
BUILD=2lu
SOURCE=http://cran.r-project.org/src/base/R-2/R-$VERSION.tar.gz
CWD=`pwd`

if [ ! -e R-$VERSION.tar.gz ]; then
 wget -c $SOURCE
fi

if ["$TMP" = ""]; then
 TMP=/tmp/txz
fi

PKG=$TMP/package-$NAME

if [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mtune=i686"
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2"
elif [ "$ARCH" = "x86_64" ]; then
  SSLKCFLAGS="-O2 -fPIC"; SLKLDFLAGS="-L/usr/lib64"; LIBDIRSUFFIX="64"
fi

if [ ! -d $TMP ]; then
 mkdir -p $TMP
fi
if [ ! -d $PKG ]; then
 mkdir -p $PKG
fi

mkdir -p $PKG/usr

cd $TMP

tar xzvf $CWD/R-$VERSION.tar.gz

cd R-$VERSION

CFLAGS="$SLKCFLAGS" \
./configure --prefix=/usr \
--enable-R-shlib \
--with-system-zlib \
--with-system-bzlib \
--with-system-pcre \
--with-blas \
--with-lapack \
--with-x
make
make prefix=$PKG/usr install
sed -i -e "s/R_HOME_DIR=.*$/R_HOME_DIR=\/usr\/lib$LIBDIRSUFFIX\/R/" $PKG/usr/bin/R
sed -i "s|/tmp/txz/package-r-project||g" $PKG/usr/bin/R
sed -i "s|/tmp/txz/package-r-project||g" $PKG/usr/lib$LIBDIRSUFFIX/R/bin/R
sed -i "s|/tmp/txz/package-r-project||g" $PKG/usr/lib$LIBDIRSUFFIX/pkgconfig/libR.pc
sed -i -e "s/R_HOME_DIR=.*$/R_HOME_DIR=\/usr\/lib$LIBDIRSUFFIX\/R/" $PKG/usr/lib$LIBDIRSUFFIX/R/bin/R


( 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/usr/man/man1
cp -a $PKG/usr/share/man/man1/* $PKG/usr/man/man1
rm -rf $PKG/usr/share
find $PKG/usr/man -type f -exec gzip -9 {} \;
chmod 755 $PKG/usr/bin/*
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

cd $CWD
mkdir -p $PKG/usr/doc/$NAME-$VERSION
cp -a *.SlackBuild slack-desc $PKG/usr/doc/$NAME-$VERSION

cd $PKG
chown -R root:root .
requiredbuilder -v -y -s $CWD $PKG
makepkg -l y -c n $CWD/$NAME-$VERSION-$ARCH-$BUILD.txz

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