#!/bin/bash

# xfce4svn.sh: keep xfce4 updated via svn
# Copyright (c) 2005 Brian Tarricone <bjt23@cornell.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License ONLY.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details at:
# http://gnu.org/licenses/gpl.html

# See below the history for configurable options.

# Revision History
#
# 0.3.0 (12 Aug 2005):
#   * Add libexo, terminal, thunar, and installit to the extras list.
#   * Add color to info/warning/error messages.
#   * Add --version/-V option.
#
# 0.2.0 (9 Aug 2005):
#   * Create and install the xfce4-svn-start script to set up env vars before
#     running startxfce4.
#
# 0.1.0 (8 Aug 2005):
#   * Initial release.


# feel free to configure these things to taste.  these are all override-able
# via command-line options.
prefix="/opt/xfce4-svn"     # where to install
sysconfdir="${prefix}/etc"  # may want to set to /etc for a system-wide install
svn_branch=                 # leave blank for 'trunk'
enable_compositor=no        # requires X.org 6.8+ with the Composite extension
                            #   enabled, and a pretty fast video card
svn_root_uri="http://svn.foo-projects.org/svn/xfce"  # anon svn
checkout_dir="/tmp/xfce4svn-co.${UID}"  # temp space to build xfce4
keep_checkout=yes           # keep checked-out files after install?
use_sudo=no                 # use 'sudo' for 'make install'?

# you can edit this to change the default modules that get installed.
MODULES=" \
    xfce4-dev-tools \
    libxfce4util \
    libxfce4mcs \
    libxfcegui4 \
    xfce-mcs-manager \
    xfce-mcs-plugins \
    xfce-utils \
    xfce4-icon-theme \
    xfce4-session \
    xfwm4 \
    xfce4-panel \
    xfdesktop \
    gtk-xfce-engine-2"

# these can be installed with the --{install,include}-extras options.
MODULES_EXTRA=" \
     xfprint \
     xfcalendar \
     xffm \
     xfwm4-themes \
     xfce4-appfinder \
     xfce4-toys \
     xfmedia \
     mousepad \
     xfce4-mailwatch-plugin \
     pyxfce \
     xfc \
     installit \
     libexo \
     terminal \
     thunar "   # that last space there is important; don't remove it!

# probably shouldn't mess with anything else unless you know what you're doing.

# don't touch me, please
VERSION="0.3.0"

green='\E[32m\033[1m'
yellow='\E[33m\033[1m'
red='\E[31m\033[1m'
normal='\033[0m'

info() {
	echo -e "${green}* ${1}${normal}"
}

warn() {
	echo -e "${yellow}* ${1}${normal}"
}

error() {
	echo -e "${red}* ${1}${normal}"
}

die() {
	error "${1}"
    [ "${keep_checkout}" = "no" ] && rm -rf "${checkout_dir}"
    exit 1
}

usage() {
    echo "Xfce4 Subversion Updater $VERSION"
    echo "Written by Brian Tarricone <bjt23@cornell.edu>, and distributed under the"
    echo "terms of the GNU General Public License, version 2."
    echo
    echo "usage: `basename ${0}` [OPTIONS]"
    echo
    echo "  --prefix=PREFIX                    Sets the install prefix."
    echo "  --sysconfdir=SYSCONFDIR            Sets the configuration install directory."
    echo "  --svn-branch=BRANCH                Sets the Subversion branch to use."
    echo "                                     Default is 'trunk'."
    echo "  --enable-compositor                Enables the compositing manager in xfwm4."
    echo "                                     This feature requires X.org 6.8+."
    echo "  --install-extras=name1[,name2...]  Installs optional extra modules."
    echo "  --include-extras=name1[,name2...]  Includes optional extra modules after"
    echo "                                     installing the base Xfce modules."
    echo "  --list-extras                      Displays a list of available extras."
    echo "  --use-sudo                         Use 'sudo' for the 'make install' step."
    echo "  --svn-root-uri=URI                 Override the default anonymous SVN root"
    echo "                                     URI."
    echo "  --checkout-dir=DIR                 Override local checkout directory."
    echo "  --clean-checkout                   Delete checked-out files after installing."
}

check_libexo_needed() {
	if echo "${extras}" | grep -e thunar -e terminal &>/dev/null; then
		if echo "${extras}" | grep -v libexo &>/dev/null; then
			warn "Modules 'thunar' and 'terminal' require 'libexo'; prepending to list."
			extras="libexo ${extras}"
		elif echo "${extras}" | grep -E '(thunar|terminal).*libexo' &>/dev/null; then
			warn "Modules 'thunar' and 'terminal' require 'libexo' before them; reordering."
			extras="libexo `echo \"${extras}\" | sed -e 's/libexo//g;'`"
		fi
	fi
}

while [ "${1}" ]; do
    if [ "${1}" = "-h" -o "${1}" = "--help" ]; then
        usage
        exit 0
    elif [ "${1}" = "-V" -o "${1}" = "--version" ]; then
    	echo "${VERSION}"
    	exit 0
    elif [ "${1:0:9}" = "--prefix=" ]; then
        prefix=${1:9}
    elif [ "${1:0:13}" = "--sysconfdir=" ]; then
        sysconfdir=${1:13}
    elif [ "${1:0:13}" = "--svn-branch=" ]; then
        svn_branch=${1:13}
    elif [ "${1}" = "--enable-compositor" ]; then
        enable_compositor=yes
    elif [ "${1:0:17}" = "--install-extras=" ]; then
        extras="`echo ${1:17} | sed -e 's/,/ /g;'`"
        for e in ${extras}; do
            echo "${MODULES_EXTRA}" | grep " ${e} " &>/dev/null
            [ $? -eq 0 ] || die "\"${e}\" is not a valid extra."
        done
		check_libexo_needed
        MODULES="${extras}"
    elif [ "${1:0:17}" = "--include-extras=" ]; then
        extras="`echo ${1:17} | sed -e 's/,/ /g;'`"
        for e in ${extras}; do
            echo "${MODULES_EXTRA}" | grep " ${e} " &>/dev/null
            [ $? -eq 0 ] || die "\"${e}\" is not a valid extra."
        done
		check_libexo_needed
        MODULES="${MODULES} ${extras}"
    elif [ "${1}" = "--list-extras" ]; then
        info "The following extras are available:"
        for e in ${MODULES_EXTRA}; do
            echo "  ${e}"
        done
        exit 0
    elif [ "${1}" = "--use-sudo" ]; then
        use_sudo=yes
    elif [ "${1:0:15}" = "--svn-root-uri=" ]; then
        svn_root_uri="${1:15}"
    elif [ "${1:0:15}" = "--checkout-dir=" ]; then
        checkout_dir="${1:15}"
    elif [ "${1}" = "--clean-checkout" ]; then
        keep_checkout=no
    else
        die "Unrecognised option: '${1}'."
    fi
    
    shift
done

if [ "x${use_sudo}" = "xyes" ]; then
	SUDO=sudo
fi

# fix occasional b0rkness
[ -z "${UID}" ] && UID=`id -u`

# find the correct 'make'
if [ -z "${MAKE}" ]; then
    MAKE=`which gmake`
    [ "${MAKE:0:1}" = "/" ] || MAKE=`which make`
    [ "${MAKE:0:1}" = "/" ] || die "A suitable version of GNU make could not be found.  Please set the environment variable 'MAKE' and try again."
fi

gtk_prefix="`pkg-config gtk+-2.0 --variable=prefix`"

export PATH="${prefix}/bin:${PATH}"
export PKG_CONFIG_PATH="${prefix}/lib/pkgconfig:${PKG_CONFIG_PATH}"
export LD_LIBRARY_PATH="${prefix}/lib:${LD_LIBRARY_PATH}"

echo -e "${green}.:. Xfce4 Subversion Updater $VERSION starting... .:.${normal}"
echo

[ ! -d ${checkout_dir} ] && (mkdir -p ${checkout_dir} || die "Unable to create dir ${checkout_dir}")

for m in ${MODULES}; do
    cd ${checkout_dir}
    
    [ ! -d ${m} ] && (mkdir ${m} || die "Unable to create ${checkout_dir}/${m}.")
    cd ${m}
    
    if [ "${svn_branch}" ]; then
        [ ! -d branches ] && (mkdir branches || die "Unable to create ${checkout_dir}/${m}/branches")
        cd branches
        co_dir="${svn_branch}"
        co_uri="${svn_root_uri}/${m}/branches/${svn_branch}"
    else
        co_dir="trunk"
        co_uri="${svn_root_uri}/${m}/trunk"
    fi

    if [ ! -d ${co_dir} ]; then
        info "Checking out module ${m}..."
        svn co "${co_uri}" || die "SVN checkout of module ${m} failed"
        cd ${co_dir}
    else
        cd ${co_dir}
        info "Attempting to uninstall old module ${m}..."
        ${SUDO} ${MAKE} uninstall
        if [ $? -eq 0 ]; then
            info "... done."
        else
            warn "... failed, continuing anyway."
        fi
        info "Updating module ${m}..."
        svn up || die "SVN update of module ${m} failed."
    fi
    
    info "... done."
    
    if [ "${m}" = "gtk-xfce-engine-2" ]; then
        my_config="--prefix=${gtk_prefix}"
    else
        my_config="--prefix=${prefix}"
    fi
    
    my_config="${my_config} --sysconfdir=${sysconfdir}"
    
    [ "${m}" = "xfwm4" -a "x${enable_compositor}" = "xyes" ] && \
            my_config="${my_config} --enable-compositor"
    
    info "Configuring ${m}..."
    if [ "${m}" = "mousepad" ]; then
        AUTOGEN_SH='xdt-autogen'  # damn you, Erik!
    else
        AUTOGEN_SH='./autogen.sh'
    fi
    ${AUTOGEN_SH} ${my_config} || die "Autogen/configure for module ${m} failed."
    info "... done."
    
    info "Building ${m}..."
    ${MAKE} clean all || die "Build for module ${m} failed."
    info "... done."
    
    info "Installing ${m}..."
    ${SUDO} ${MAKE} install || die "Install for module ${m} failed."
    info "... done."
done

# create the run script

cat >/tmp/xfce4-svn-start.${UID} <<EOF
#!/bin/bash

xfce_prefix="${prefix}"
xfce_sysconfdir="${sysconfdir}"

export PATH="\${xfce_prefix}/bin:\${PATH}"
export LD_LIBRARY_PATH="\${xfce_prefix}/lib:\${LD_LIBRARY_PATH}"
export PKG_CONFIG_PATH="\${xfce_prefix}/lib/pkgconfig:\${PKG_CONFIG_PATH}"

test -z "\${XDG_DATA_DIRS}" && XDG_DATA_DIRS="/usr/local/share:/usr/share"
export XDG_DATA_DIRS="\${xfce_prefix}/share:\${XDG_DATA_DIRS}"

test -z "\${XDG_CONFIG_DIRS}" && XDG_CONFIG_DIRS="/etc/xdg"
export XDG_CONFIG_DIRS="\${xfce_sysconfdir}/xdg:\${XDG_CONFIG_DIRS}"

exec \${xfce_prefix}/bin/startxfce4
EOF

$SUDO mv /tmp/xfce4-svn-start.${UID} ${xfce_prefix}/bin/xfce4-svn-start ||
	warn "Unable to install xfce4-svn-start script."

# and we're finished

[ "${keep_checkout}" = "no" ] && rm -rf "${checkout_dir}"

echo "Build complete."
[ "${keep_checkout}" != "no" ] && \
    info "Build files were left in ${checkout_dir}."
echo
info "You may run ${xfce_prefix}/bin/xfce4-svn-start to start Xfce4 SVN."

