#!/bin/bash

##
##
##  4store install script for Debian/Ubuntu and Redhat/CentOS families
##  builds either specified version of latest from github (see $fs_ver)
##
##  Ian Millard, 2011
##
##

# check latest versions
raptor=raptor2-2.0.15           # http://librdf.org/raptor/
rasqal=rasqal-0.9.33            # http://librdf.org/rasqal/
fs_ver=v1.1.6			# use "master" for Git HEAD, or specific version eg "v1.1.5"

##
## install required libraries
##
if [ -f /usr/bin/apt-get ]
then
	# looks like a Debian or Ubuntu distro
	sudo apt-get -y install build-essential autoconf automake libpcre3-dev libtool libglib2.0-dev ncurses-dev libreadline-dev uuid-dev libxml2-dev

elif [ -f /usr/bin/yum ]
then

	# looks like a RHEL, CentOS or Fedora distro
	sudo yum -y groupinstall 'Development Tools'
	sudo yum -y install libxml2-devel ncurses-devel readline-devel uuid-devel libuuid-devel glib2-devel pcre-devel

else

	# abort, if we don't have --manual-libraries set
	echo
	echo "Sorry, I could not find your package manager."
	echo "Required libraries cannot be automatically installed."
	echo 
	echo "Please install build tools and 4store dependencies manually"
	echo "see http://4store.org/trac/wiki/Dependencies"
	echo
	echo "Then run $0 --manual-libraries"
	echo
	[[ "$1" != "--manual-libraries" ]] && exit 1
fi

# ensure we're picking up both 64bit libraries and those from /usr/local/lib/
# (which is where raptor and rasqal install themselves)
export PKG_CONFIG_PATH="/usr/lib64/pkgconfig:/usr/local/lib64/pkgconfig:/usr/lib/pkgconfig:/usr/local/lib/pkgconfig"
base=`pwd`

##
## raptor
##
cd $base
if [ ! -f $raptor.tar.gz ]
  then wget http://download.librdf.org/source/$raptor.tar.gz
  else rm -rf ./$raptor
fi
tar -zxf $raptor.tar.gz
ln -s $raptor raptor
cd raptor
./configure
make
sudo make install

##
## rasqal
##
cd $base
if [ ! -f $rasqal.tar.gz ]
  then wget http://download.librdf.org/source/$rasqal.tar.gz
  else rm -rf ./$rasqal
fi
tar -zxf $rasqal.tar.gz
ln -s $rasqal rasqal
cd rasqal
./configure
make
sudo make install

sudo ldconfig /usr/local/lib/

##
##  4store
##
cd $base
if [ ! -f 4store-$fs_ver.tar.gz ]
  then wget -O 4store-$fs_ver.tar.gz http://github.com/garlik/4store/archive/$fs_ver.tar.gz
  else rm -rf ./4store-$fs_ver 4store
fi
mkdir 4store-$fs_ver
ln -s 4store-$fs_ver 4store
cd 4store-$fs_ver
tar zxf ../4store-$fs_ver.tar.gz --strip-components 1
if [ "$fs_ver" == "master" ]
then
	echo "`date +%F`" > .version;
else
	echo $fs_ver | sed 's/^v\([0-9]\)/\1/' > .version;
fi
libtoolize
aclocal
autoconf
autoheader
automake --add-missing
./autogen.sh
./configure
make
sudo make install

##
## create basic /etc/4store.conf if it doesn't exist
##
[[ ! -f /etc/4store.conf ]] && sudo tee /etc/4store.conf > /dev/null <<EOF
[4s-boss]
  discovery = sole
  nodes = localhost
EOF
