#!/bin/sh
# MIT/X Consortium License
#
# 2010 Petr Sabata <psabata@redhat.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#

version=5.8.2
release=4.fc12
sources=/usr/src/dwm-user-${version}-${release}
bindir=~/.dwm
builddir=~/.dwmbuild
config=${bindir}/config.h
modified=${bindir}/modified
buildver=${bindir}/version

function run_custom {
    echo "Running user dwm..." 1>&2
    ${bindir}/dwm
}

function run_system {
    echo "Running system dwm..." 1>&2
    dwm
}

function rebuild {
    if [ ! -d ${sources} ]; then
        echo "Cannot find sources in ${sources}. Not rebuilding." 1>&2
    else
        echo -n "Rebuilding dwm... " 1>&2
        rm -rf ${builddir}
        cp -R ${sources} ${builddir}
        cp ${config} ${builddir}/config.def.h
        cd ${builddir}
        make 2>&1 > ${builddir}/build.log
        if [ "$?" -ne 0 ]; then
            echo "FAILED" 1>&2
            echo "See ${builddir}/build.log." 1>&2
            exit 1
        else
            echo "OK" 1>&2
        fi
        mv ${builddir}/dwm ${bindir}
        rm -rf ${builddir}
        echo `stat -c %Y "${config}"` > ${modified}
        echo "${version}-${release}" > ${buildver}
    fi
}

mkdir -p ${bindir}
if [ -f ${config} ]; then
    if [ ! -f ${modified} ] || [ "`cat ${modified}`" -lt `stat -c %Y ${config}` ] ||
       [ ! -f ${buildver} ] || [ "`cat ${buildver}`" != "${version}-${release}" ]; then
        rebuild
    fi
    run_custom
elif [ -f ${bindir}/dwm ]; then
    run_custom
else
    run_system
fi
