#!/bin/sh
export LANG=C
SRC_DIR=/home/archives/source/kde
CWD=`pwd`
export WORK=$CWD/work
export WORK_PKG=$CWD/work/pkg
export CFLAGS="-O2"
export MAKEFLAGS="-j 6"
PKG_NAME=kdegames
SRC_VERSION=4.3.3
ARCHI_VERSION=i586
BUILD_VERSION=P1
SRC_FILE="${PKG_NAME}-${SRC_VERSION}.tar.bz2"

################################################
# Keep variables below.
################################################
export PATH=$PATH:/opt/kde/bin:/usr/bin:/opt/www/htdig/bin:/usr/X11R7/bin
export PKG_CONFIG_PATH=/usr/X11R7/lib/pkgconfig:/usr/lib/pkgconfig:/opt/kde/lib/pkgconfig
export XDG_DATA_DIRS=/opt/kde/share:/usr/share:/usr/local/share
export BOOST_ROOT=/usr
export BOOST_INCLUDEDIR=/usr/include/boost-1_38

###############################################
# Clean up. remove work directory
###############################################
# remove work directory
if [ -d $WORK ]; then
  rm -rf $WORK;
fi;
mkdir $WORK

# check source file
# if not exist, get files.
for i in $SRC_FILE ; do 
  if [ ! -f $SRC_DIR/$i ]; then
    (cd $SRC_DIR; wget ftp://ftp.kde.org/pub/kde/stable/$SRC_VERSION/src/$i);
  fi;
done

##############################################
# Untar source.tar.bz2 and apply patches.
##############################################

echo "Building ${PKG_NAME}-${SRC_VERSION}.tar.bz2..."
cd $WORK
tar xjvf $SRC_DIR/$SRC_FILE

###############################################
# Build
###############################################

mkdir build
cd build

cmake ../${PKG_NAME}-${SRC_VERSION} -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/opt/kde
if [ $? -ne 0 ]; then
	echo "Build(cmake) failed"
	exit 255
fi

make
if [ $? -ne 0 ]; then
	echo "Build(make) failed"
	exit 255
fi

##############################################
# Make package trees
##############################################
make install DESTDIR=$WORK_PKG

mkdir -p $WORK_PKG/usr/share/doc/${PKG_NAME}-${SRC_VERSION}
cd ../${PKG_NAME}-${SRC_VERSION}
cp -ap AUTHORS COPYING COPYING-DOCS COPYING.LIB INSTALL \
  README \
  $WORK_PKG/usr/share/doc/${PKG_NAME}-${SRC_VERSION}
gzip -9 $WORK_PKG/usr/share/doc/${PKG_NAME}-${SRC_VERSION}/*
chown -R root.root $WORK_PKG/usr/share/doc/${PKG_NAME}-${SRC_VERSION}
strip $WORK_PKG/opt/kde/bin/*
strip $WORK_PKG/opt/kde/lib/*

mkdir -p $WORK_PKG/usr/share/doc/${PKG_NAME}-${SRC_VERSION}/build
cp -ap $CWD/PlamoBuild \
  $WORK_PKG/usr/share/doc/${PKG_NAME}-${SRC_VERSION}/build

# Additional doinst.
mkdir -p $WORK_PKG/install
cat << EOF >> $WORK_PKG/install/initpkg
if [ -f /opt/kde/bin/plamo_update_kde.sh ]; then
	/bin/bash /opt/kde/bin/plamo_update_kde.sh
fi
EOF

##############################################
# Make package trees
##############################################
#make package
cd $WORK_PKG
echo "y
1
" | makepkg ${PKG_NAME}-${SRC_VERSION}.tgz
mv ${PKG_NAME}-${SRC_VERSION}.tgz $CWD/${PKG_NAME}-${SRC_VERSION}-${ARCHI_VERSION}-${BUILD_VERSION}.tgz
cd $CWD
