#!/bin/sh -x

WITH_SUBTLY="YES"

CWD=$(pwd)
PRGNAM=$(basename $CWD)
VERSION=hg$(date +%Y.%m.%d_%H.%M)
BUILD=1


TAG=cyco
TMP=/tmp/$TAG
PKG=$TMP/pkg-$PRGNAM
OUTPUT=/tmp

ARCH=$(uname -m)

REPOSITORIES=/home/installs/SlackBuilds/repositories
PREFIX=/usr

[ -e $PKG ] && rm -fr $PKG

function get_sources_here() {
    COMPONENT=$1

    [ -e ./$COMPONENT-$VERSION ] && rm -fr ./$COMPONENT-$VERSION

    if [ -e $CWD/$COMPONENT-$VERSION.tar.?z* ]; then
        tar xf $CWD/$COMPONENT-$VERSION.tar.?z*
    else
        if [ ! -e $REPOSITORIES/$COMPONENT ]; then
            hg clone http://hg.subtle.de/$COMPONENT $REPOSITORIES/$COMPONENT
        else
            ( cd $REPOSITORIES/$COMPONENT
                hg pull -u
            )
        fi
        cp -R $REPOSITORIES/$COMPONENT ./$COMPONENT-$VERSION
    fi
}

function build_install() {
    COMPONENT=$1

    ( cd ./$COMPONENT-$VERSION
        RAKE_OPTIONS=$([ ! -e ./Rakefile ] && echo " -f $REPOSITORIES/$COMPONENT/Rakefile ")

        rake $RAKE_OPTIONS destdir=$PKG prefix=$PREFIX config

        rake $RAKE_OPTIONS destdir=$PKG prefix=$PREFIX build

        rake $RAKE_OPTIONS destdir=$PKG prefix=$PREFIX install
    )
	[ -e $PKG$PREFIX/share/man ] && cp -a $PKG$PREFIX/share/man $PKG$PREFIX && rm -fr $PKG$PREFIX/share/man
    find $PKG$PREFIX/man -not -name "*.gz" -exec gzip -9 {} \;
}

mkdir -p $TMP
( cd $TMP
    get_sources_here subtle
    build_install subtle
    get_sources_here sur
    build_install sur
    if [ $WITH_SUBTLY == "YES" ]; then
        get_sources_here subtly
        build_install subtly
    fi
)

mkdir -p $PKG$PREFIX/share/subtle/
( cd $PKG$PREFIX/share/subtle/
    get_sources_here subtle-contrib
    mv subtle-contrib-$VERSION subtle-contrib
    chmod +x subtle-contrib/*.rb
    
    get_sources_here sublets
    mv sublets-$VERSION sublets
    ( cd sublets
        rake build
    )
)

mkdir -p $PKG/etc/X11/xinit/
cp $CWD/xinitrc.$PRGNAM $PKG/etc/X11/xinit/
chmod +x $PKG/etc/X11/xinit/xinitrc.$PRGNAM

find $PKG -name .hg\* -exec rm -fr {} \;

( cd $PKG
    mkdir -p install
    cat <<EOF > install/slack-desc
$PRGNAM: $PRGNAM (is a grid-based manual tiling window manager)
$PRGNAM: with a strong focus on easy but customizable look and feel. In comparison to
$PRGNAM: other tiling windows managers, subtle has no automatic tiling of the screen
$PRGNAM: size in any way, instead windows are arranged according to positions inside
$PRGNAM: of a grid - these positions are called gravities.
$PRGNAM: http://subforge.org
$PRGNAM:                                -------
$PRGNAM: includes sur (Subtle User Repository ("rubbygem-like" repository of sublets))
$PRGNAM: includes subtly, a Web browser
$PRGNAM: required gems:
$PRGNAM: curb sinatra datamapper archive-tar-minitar ffi subtle-graph subtle-dynamic_icon
EOF

    makepkg -l y -c n $OUTPUT/$PRGNAM-$(echo $VERSION | tr - .)-$ARCH-$BUILD$TAG.txz
)