#!/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.6.1 (5 Nov 2007):
#   * Add libxfce4menu module
#   * move libexo and thunar out of extras and into main modules
#   * put libexo before xfce4-panel, as the panel apparently depends
#     on it now
#
# 0.6.0 (28 Sep 2006):
#   * Add install tracking and only uninstall the previous version right
#     before doing 'make install'
#   * remove the enable-compositor option, as the compositor is built by
#     default now
#   * remove xfce4-mailwatch-plugin from extras since it's in the goodies
#     repository now
#   * change --disable-thunar-vfs option passed to xfdesktop to
#     --disable-file-icons
#
# 0.5.0 (13 Mar 2006):
#   * Add --enable-file-icons option which moves libexo and thunar
#     compilation before xfdesktop
#   * Add --start-with option to resume installation at a particular
#     module
#   * Remove xdt-autogen hack for mousepad, which is fixed
#
# 0.4.0 (30 Oct 2005):
#   * Update default SVN root URI due to Xfce SVN move
#   * Don't try to download xfce4-dev-tools in branches other than trunk.
#   * Quote some file/directory names just in case.
#
# 0.3.1 (2 Sep 2005):
#   * Fix bad references to ${xfce_prefix} --> ${prefix}.
#   * Fix xfce4-svn-start script perms.
#
# 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'
svn_root_uri="http://svn.xfce.org/svn/xfce"  # anon svn
checkout_dir="/tmp/xfce4-checkout.$UID"      # temp space to build xfce4
keep_checkout=yes           # keep checked-out files after install?
use_sudo=yes                # use 'sudo' for 'make install'?
enable_file_icons=yes       # whether or not to enable file icons in xfdesktop

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

# these can be installed with the --{install,include}-extras options.
MODULES_EXTRA=" \
     xfprint \
     xfcalendar \
     xfwm4-themes \
     xfce4-appfinder \
     xfmedia \
     mousepad \
     pyxfce \
     xfc \
     installit \
     terminal "   # 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.6.1"

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 "  --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."
    echo "  --enable-file-icons                Uses Thunar to add file icons to xfdesktop."
    echo "                                     This will compile libexo and thunar before"
    echo "                                     xfdesktop.  Note that this option will"
    echo "                                     be enabled automatically if an existing"
    echo "                                     installation of Thunar is detected."
    echo "  --disable-file-icons               Disable xfdesktop file icon support,"
    echo "                                     regardless of whether or not Thunar"
    echo "                                     was found."
    echo "  --start-with=MODULE                Skip all modules before MODULE."
}

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: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
        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
        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
    elif [ "${1}" = "--enable-file-icons" ]; then
        enable_file_icons=yes
    elif [ "${1}" = "--disable-file-icons" ]; then
        enable_file_icons=no
    elif [ "${1:0:13}" = "--start-with=" ]; then
        start_with="${1:13}"
    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

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

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

# we now always build thunar before xfdesktop.  we only check for
# dbus-glib to see if we have the dependencies available, and also
# take --disable-file-icons into account
have_icon_deps=yes
pkg-config --exists dbus-glib-1 &>/dev/null || have_icon_deps=no
if [ "x${enable_file_icons}" = "xno" -o "x${have_icon_deps}" = "xno" ]; then
    xfdesktop_configure_args="--disable-file-icons"
fi

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
    if [ "${start_with}" -a "${start_with}" != "${m}" ]; then
        continue
    else
        unset start_with
    fi

    cd "${checkout_dir}"

    [ ! -d "${m}" ] && (mkdir "${m}" || die "Unable to create ${checkout_dir}/${m}.")
    cd "${m}"

    if [ "${svn_branch}" ]; then
        [ "${m}" = "xfce4-dev-tools" ] && continue
        [ ! -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}"
        if [ ! -f .xfce4svn-inst-filelist ]; then
            info "Attempting to uninstall old module ${m}..."
            ${SUDO} make uninstall
            if [ $? -eq 0 ]; then
                info "... done."
            else
                warn "... failed, continuing anyway."
            fi
        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}" = "xfdesktop" ] && \
            my_config="${my_config} ${xfdesktop_configure_args}"

    info "Configuring ${m}..."
    ./autogen.sh ${my_config} || die "Autogen/configure for module ${m} failed."
    info "... done."

    info "Building ${m}..."
    ${MAKE} ${MAKEOPTS} clean all || die "Build for module ${m} failed."
    info "... done."

    if [ -f .xfce4svn-inst-filelist ]; then
        info "Uninstalling previous version of ${m}..."
        for file in `cat .xfce4svn-inst-filelist`; do
            if [ -f "${file}" ]; then
                ${SUDO} rm -fv "${file}"
            elif [ -d "${file}" ]; then
                ${SUDO} rmdir -v "${file}"
            fi
        done
        info "... done."
    fi

    info "Creating list of files for later uninstall for ${m}..."
    [ -d .xfce4svn-destdir ] && rm -rf .xfce4svn-destdir
    make install DESTDIR=`pwd`/.xfce4svn-destdir &&
    ( cd .xfce4svn-destdir &&
      find | cut -d. -f2 >../.xfce4svn-inst-filelist )
    rm -rf .xfce4svn-destdir
    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} "${prefix}/bin/xfce4-svn-start" ||
	warn "Unable to install xfce4-svn-start script."
chmod 755 "${prefix}/bin/xfce4-svn-start" >/dev/null 2>&1

# 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 ${prefix}/bin/xfce4-svn-start to start Xfce4 SVN."
