#! /usr/bin/env bash
################################################################################
# Updates and recompiles a local KDE tree from SVN                             #
# (c) 2000, 2001, 2002, 2003 by Frerich Raabe <raabe@kde.org>                  #
# (c) 2002, 2003 by Stephan Kulow <coolo@kde.org>                              #
################################################################################
# Do not edit this file, change kde-buildrc instead!                           #
################################################################################

# These strings are defined as variables to make the output look more
# consistent.
#
str_okay="done!"
str_error="failed!"

# The variables whose name is prefixed with ERR_ hold the error codes which
# are returned by the script and depend on the reason for aborting the
# execution.
#
# No error has been noticed, everything seems to be fine.
#
err_no_error="0"

# Could not change into a directory of a module - wrong owner/access
# settings?
#
err_change_into_mod_dir="1"

# Could not find the file 'Makefile.in' for a module, mostly happens if
# 'make -f Makefile.cvs' hasn't been executed for a module.
#
err_no_makefile_in="2"

# The 'configure' command failed for a module because the system doesn't
# support certain features - I hope you activated logfile generation... ;)
#
err_configure_fail="3"

# The compilation of a module failed - if the module is defined in
# $critical_modules (see below) the execution is aborted, otherwise the script
# will continue with the next module.
#
err_compile_fail="4"

# The installation of a module failed - this mostly happens if there's not
# enough free disk space on the partition which $KDEDIRS is mounted to.
#
err_install_fail="5"

# The $KDESRCDIR variable wasn't set or contains a non-existant directory.
#
err_inv_kdesrcdir="6"

# The $QTDIR variable wasn't set, points to a non-existant directory or
# doesn't contain a bin/, lib/, or include/ subdirectory.
#
err_inv_qtdir="7"

# ....

# The configuration file couldn't be found.
#
err_no_config="11"

# You can't mix CVS_CLEAN and INCREMENTAL_BUILD
#
err_cvsclean_incremental="12"

# You can't mix BUILD_CLEAN and INCREMENTAL_BUILD
#
err_buildclean_incremental="13"

# Certain modules depend on others - those "base" modules which are required
# by others to compile and/or run should be listed here to ensure that the
# script is aborted in case on of these modules doesn't build.
# These modules needs to be build and installed in this specific order!
#
critical_modules="arts kdelibs kdebase"

# Internal variable, do not change.
#
dateformat="`date +%Y%m%d`"

# Private variables fro controlling kppp
#
we_started_kppp="FALSE"

# Connects to the internet using kppp if desired
#
kppp_connect()
{
if [ "$USE_KPPP" = "TRUE" ]; then
	kppp_process=`dcopfind -a kppp-*`
	if [ "$kppp_process" = "" ]; then
		#kppp not running
		kppp > /dev/null 2>&1 &
		sleep $KPPP_LOAD_TIME
		`dcop $(dcopfind -a kppp-*) KpppIface beginConnect`
		#wait for a while
		sleep $KPPP_CONNECT_TIME
		kppp_connected=`dcop $(dcopfind -a kppp-*) KpppIface isConnected`
		if [ "$kppp_connected" = "true" ]; then
			we_started_kppp="TRUE"
			echo Connected OK
		else
			echo Could not connect, maybe you need to increase KPPP_CONNECT_TIME
		fi
		
	else
		kppp_connected=`dcop $(dcopfind -a kppp-*) KpppIface isConnected`
		if [ "$kppp_connected" = "false" ]; then
			#Start a connection
			`dcop $(dcopfind -a kppp-*) KpppIface beginConnect`
			#wait for a while
			sleep $KPPP_CONNECT_TIME
			kppp_connected=`dcop $(dcopfind -a kppp-*) KpppIface isConnected`
			if [ "$kppp_connected" = "true" ]; then
				we_started_kppp="TRUE"
				echo Connected OK
			else
				echo Could not connect, maybe you need to increase KPPP_CONNECT_TIME
			fi
		else
			echo Kppp is already connected to the internet
		fi
	fi
fi
}

# Disconnects from the internet using kppp if desired
#
kppp_disconnect()
{
if [ "$USE_KPPP" = "TRUE" ]; then
	if [ $(dcopfind -a kppp-*) = "" ]; then
		#kppp not running
		echo Kppp was not running so cannot be disconnected
	else
		if [ "$we_started_kppp" = "TRUE" ]; then
			echo Disconnecting kppp
			`dcop $(dcopfind -a kppp-*) KpppIface disconnect`
		else
			echo We didnt connect using kppp so we wont disconnect
		fi
	fi
fi
}

# This method gives some kind of status message in the title bar of Konsole,
# xterm, etc.. Thanks have to go to Malte Starostik
# <malte@kde.org> for the code :-)
set_title() {
  which printf > /dev/null 2>&1 || return
  if ([ "$TERM" = "xterm" ] || [ "$TERM" = "xterm-color" ] || [ "$TERM" = "screen" ]) && tty -s; then
    printf "\033]0;$1\007"
  fi
}

# moves a log file to be named $1, so one can see on first glance
move_logfile() {
  rename_logfile=`echo $logfile | sed -e "s,-build-,-$1-,"`
  mv "$logfile" "$rename_logfile"
  logfile=$rename_logfile
}

# Executes the given command, logging the output to $logfile if requested.
#
log_cmd() {
  if [ -n "$logfile" ]; then
    eval "$1 >> $logfile 2>&1"
  else
    eval "$1"
  fi
  return $?
}

module_variable() {
  eval "$1=\$BASE_$1"
  varname="$1_"`echo $module|tr a-z A-Z|tr - _|sed "s/\(.*\)-[0-9]*/\1/g"`; # e.g. $1_ARTS etc.
  varvalue=`eval echo '$'$varname`
  if [ -n "$varvalue" ]; then
    eval "$1=\"$varvalue\""
  fi
}

# Inserts a "-> blah <---" style separator into $logfile, and starts a timer
log_section() {
  [ -z "$logfile" ] && return 0
  len=`echo $1 | wc -m | sed -e "s,^ *,,"`
  echo "------------------------------------------------------------------------" \
    | sed -e "s,^,-> $1 <," -e "s,.\{$len\}$,," >> $logfile 2>&1
  starttime=`date +%s`
}

# Computes the time elapsed since the last log_section call,
# inserts a "----" separator, and the time needed, into $logfile
log_endsection() {
  [ -z "$logfile" ] && return 0
  compute_time
  echo "----------------------------------------------------------------------------" >> $logfile 2>&1
  printf "%s for module %s done. Time needed: %02d:%02d:%02d\n" "$1" $module $hours $minutes $seconds >> $logfile 2>&1
  echo "" >> $logfile 2>&1
}

# This function computes the time which was needed for a certain task, using
# expr (instead of shell-specific features) for portability.
#
compute_time() {
  duration=`expr \`date +%s\` - $starttime`
  hours=`expr $duration / 3600`
  minutes=`expr $duration % 3600 / 60`
  seconds=`expr $duration % 60`
}

prepare_update() {
  # This checks whether the user wants a certain branch and generates the
  # command line.
  #
  cmd_update="svn"
  if test -d $KDESRCDIR/$module; then
    test -z "$SUBDIR" && { cmd_update="$cmd_update update" ; return; }
    cmd_update="$cmd_update switch -r HEAD"
  else
    cmd_update="$cmd_update co"
  fi
  if [ -z "$ACCOUNT" ]; then
    cmd_update="$cmd_update $ANONSVNROOT$SUBDIR"
  else
    cmd_update="$cmd_update"
    if [ "$SSHACCOUNT" = "yes" ]; then
      cmd_update="$cmd_update svn+ssh://$ACCOUNT@svn.kde.org/home/kde$SUBDIR"
    else
      cmd_update="$cmd_update https://$ACCOUNT@svn.kde.org/home/kde$SUBDIR"
    fi
  fi
  if [ -n "$CHECKOUT_PARTIAL" -a "$1" = "toponly" ]; then # TODO
    cmd_update="$cmd_update -N"
  fi
  if test ! -d $KDESRCDIR/$module; then
    cmd_update="$cmd_update $module"
  fi
}

# This function installs a compiled CVS module.
#
install_module() {
  echo -n "  Installing..."
  set_title "Installing module $module..."
  log_section "Installation"

  if log_cmd "$cmd_make_install"; then
    log_endsection "Installation"
    if [ -n "$KDELOGDIR" ]; then
      echo "Build of module $module successfully finished at `date +%c`" >> $logfile
      [ -n "$cmd_compress" ] && eval "$cmd_compress $logfile"
    fi
    echo "$str_okay"
    echo "Module $module successfully installed in $KDEDIRS!"
    move_logfile "finished"
  else
    echo "$str_error"
    move_logfile "failed"
    [ -n "$cmd_compress" ] && eval "$cmd_compress $logfile"
    [ $critical -eq 0 ] || exit $err_compile_fail
  fi
}

make_makefile_cvs() {
  cmd_make_makefile_cvs="$MAKE -f Makefile.cvs"
  if [ "$NICECOMPILE" = yes ]; then
    cmd_make_makefile_cvs="nice $cmd_make_makefile_cvs"
  fi
  unset UNSERMAKE || true
  if [ -n "$USE_UNSERMAKE" ] && \
     !(echo $NO_UNSERMAKE_MODULES | grep $module > /dev/null 2>&1); then
    export UNSERMAKE=$USE_UNSERMAKE 
  fi

  if [ "$INCREMENTAL_BUILD" = "yes" -a -e "Makefile.in" ]; then
    cmd_make_makefile_cvs="echo Warning: no Makefile.cvs for module $module - as requested"
  fi

  if log_cmd "$cmd_make_makefile_cvs"; then
    echo "$str_okay"
  else
    echo "$str_error"
  fi
}

# Disable zsh feature
CDPATH=

# Get current configuration, bail out if it couldn't be found.
# Search order is $PWD:$HOME:`dirname $0`
# The name in $HOME is .kde-buildrc  (note the leading '.')
if [ -e "$PWD/kde-buildrc" ]; then
  rc_file="$PWD/kde-buildrc"
else
  if [ -e "$HOME/.kde-buildrc" ]; then
    rc_file="$HOME/.kde-buildrc"
  else
    if [ -e "`dirname $0`/kde-buildrc" ]; then
      rc_file="`dirname $0`/kde-buildrc"
    else
      echo "ERROR: Cannot locate configuration file kde-buildrc!"; exit $err_no_config
    fi
  fi
fi

INCREMENTAL_BUILD="no"

. $rc_file

if [ "${INCREMENTAL_BUILD}" = "yes" -a "${CVS_CLEAN}" = "yes" ]; then
    echo "ERROR: Cannot use CVS_CLEAN=\"yes\" and INCREMENTAL_BUILD=\"yes\" together!"; exit $err_cvsclean_incremental
fi

if [ "${INCREMENTAL_BUILD}" = "yes" -a "${BUILD_CLEAN}" = "yes" ]; then
    echo "ERROR: Cannot use BUILD_CLEAN=\"yes\" and INCREMENTAL_BUILD=\"yes\" together!"; exit $err_buildclean_incremental
fi

domakecvs=1
dosvnupdate=1
dousage=0
specifiedModules=""

# Parse args
#
while [ $# != 0 ]
do
  arg=$1
  case "$arg" in
    --help)
        dousage=1
        break ;;
    --version)
        # Show version
        echo "$0 version 0.8.15"
        exit $err_no_error ;;
    --no-update)
        dosvnupdate=0 ;;
    --no-check)
	domakecvs=0 ;;
    --incremental)
        INCREMENTAL_BUILD="yes"
        ;;
    --full)
        INCREMENTAL_BUILD="no"
        ;;
    -*)
        echo "Unhandled option $arg"
        dousage=1
        break ;;
    *) 
        specifiedModules="$specifiedModules $arg" ;;
  esac
  shift
done

# Show help info
if [ "$dousage" -eq 1 ]; then
  echo "usage: $0 [--options] [modules]"
  echo "--no-update    Do not update from SVN."
  echo "--no-check     Do not re-run Makefile.cvs."
  echo "--incremental  Start make right after update - risky. This also"
  echo "               disables the BUILD_CLEAN and CVS_CLEAN options."
  echo "--full         Do full setup even when INCREMENTAL_BUILD is set."
  echo "--help         Show this message."
  exit $err_no_error
fi

# Expand ~
QTDIR=`echo "$QTDIR" | sed -e "s,^\~/,$HOME/,"`
KDESRCDIR=`echo "$KDESRCDIR" | sed -e "s,^\~/,$HOME/,"`
KDEBUILDDIR=`echo "$KDEBUILDDIR" |sed -e "s,^\~/,$HOME/,"`
KDEDIRS=`echo "$KDEDIRS" |sed -e "s,^\~/,$HOME/,"`
KDELOGDIR=`echo "$KDELOGDIR" |sed -e "s,^\~/,$HOME/,"`

# Make sure some paths are according to the rc file. Note that there are AFAIK
# UNIX flavors which don't support LD_LIBRARY_PATH
PATH=$QTDIR/bin:$KDEDIRS/bin:$PATH
MANPATH=$QTDIR/doc/man:$MANPATH
LD_LIBRARY_PATH=$KDEDIRS/lib:$QTDIR/lib:$LD_LIBRARY_PATH

if [ -n "$USE_UNSERMAKE" ]; then
  if [ -n "$MAKE" ]; then
     echo "overwriting MAKE=$USE_UNSERMAKE"
  fi
  MAKE=$USE_UNSERMAKE
  UNSERMAKE_PATH=`dirname $USE_UNSERMAKE`
  PATH=$UNSERMAKE_PATH:$PATH
fi

if [ -z "$MAKE" ]; then
  MAKE=make
fi

if [ -n "$specifiedModules" ]; then
  # In case someone with a kdebase dir in $PWD does autocompletion..
  modules=$( echo $specifiedModules | sed -e 's/\///g' )
else
  if [ "$ONLYLISTEDMODULES" = yes ]; then
    if [ "$USEKDESUPPORT" = yes ]; then
      modules="kdesupport $critical_modules $KDEMODULES"
    else
      modules="$critical_modules $KDEMODULES"
    fi
  else
    modules="$critical_modules"
    # This generates in 'modules' a list of the modules which shall be updated.
    #
    potential_modules=`find $KDESRCDIR -type d -mindepth 1 \
        -maxdepth 1 -follow | sed -e "s@.*/?*@@"`
    for module in $potential_modules; do
      if [ -d $KDESRCDIR/$module/CVS -a -w $KDESRCDIR/$module ] \
          && !(echo $EXCLUDE | grep -q $module) \
          && !(echo $modules | grep -q $module) ; then
         modules="$modules $module"
      fi
    done
  fi
fi

# Various checks to ensure that the user didn't specify invalid data which
# would make our script break.
#
if [ -n "$KDELOGDIR" -a ! -d "$KDELOGDIR" ]; then
  if ! mkdir -p "$KDELOGDIR" > /dev/null 2>&1; then
    echo "WARNING: Could not create logfile-directory."
    echo "WARNING: Logfile generation deactivated."
    KDELOGDIR=""
  fi
else
  if [ -n "$KDELOGDIR" -a ! -w "$KDELOGDIR" ]; then
    echo "WARNING: Could not obtain write access to specified logfile-directory."
    echo "WARNING: Logfile generation deactivated."
    KDELOGDIR=""
  fi
fi

if [ -n "$KDELOGDIR" ]; then
  str_error="$str_error Check the logfile in $KDELOGDIR for further information."
fi

if [ ! -d "$KDESRCDIR" ]; then
  echo "ERROR: Invalid source directory specified!"; exit $err_inv_kdesrcdir
fi
if [ ! -d "$QTDIR" -o ! -d "$QTDIR/lib" -o ! -d "$QTDIR/bin" -o ! -d "$QTDIR/include" ]; then
  echo "ERROR: Invalid Qt directory specified!"; exit $err_inv_qtdir
fi

if [ "$COMPRESSLOGS" = yes ]; then
  if which bzip2 > /dev/null 2>&1; then
    cmd_compress="`which bzip2` -f "
  else
    if which gzip > /dev/null 2>&1; then
      cmd_compress="`which gzip` -f "
    else
      echo "WARNING: Neither bzip2 nor gzip was found, disabling compression of logfiles."
      cmd_compress=""
    fi
  fi
fi

if which sudo > /dev/null 2>&1; then
  cmd_sudo="sudo"
else
  cmd_sudo="su -c"
fi

# Clean the installation directory if selected.
#
if test "$INSTALLFROMSCRATCH" = yes && test -z "$specifiedModules" ; then
  mkdir -p $KDEDIRS 2> /dev/null
  if [ ! -w $KDEDIRS ]; then
    echo "Enter the root password to clean the installation directory."
    echo "WARNING: All files and directories in $KDEDIRS will be deleted!"
    echo -n "Please enter root "
    eval "$cmd_sudo rm -rf $KDEDIRS/*"
  else
    rm -rf $KDEDIRS/*
  fi
fi

# Optionally activate cheap tweaks.
#
if [ "$TWEAKCOMPILE" = yes ]; then
  CFLAGS="-O0"
  CXXFLAGS="-O0"
  export CFLAGS CXXFLAGS
fi

# Preprocess configuration keys, expand keywords (DISTCC)
#
if echo $MAKE_OPTS_COMPILE | grep DISTCC > /dev/null; then
  if [ -n "$DISTCC_HOSTS" ]; then
    hosts=0
    for host in $DISTCC_HOSTS; do
      hosts=$((${hosts} + 1))
    done
    hosts=$((${hosts} * 2))
  else
    hosts=1
  fi
  MAKE_OPTS_COMPILE=`echo $MAKE_OPTS_COMPILE | sed -e "s,DISTCC,$hosts,"`
fi

if echo $MAKE_OPTS_COMPILE | grep TEAMBUILDER > /dev/null; then
  if ! which tbcompiler > /dev/null 2>&1; then
    echo "TEAMBUILDER is not in PATH and OPTS_COMPILE has TEAMBUILDER"
    exit 1
  fi
  hosts=`tbcompiler -joblimit`
  if [ -z "$hosts" ]; then
    hosts=1
  fi
  MAKE_OPTS_COMPILE=`echo $MAKE_OPTS_COMPILE | sed -e "s,TEAMBUILDER,$hosts,"`
fi

#Connect to the internet before we start enything
#
kppp_connect

# Guess what? We'll finally start checking out the modules. :-)
#
# If we want to use unsermake, update that at the very beginning, so that
# all the modules make use of the most recent unsermake version.
#
if [ -n "$USE_UNSERMAKE" ] && [ "$dosvnupdate" -eq 1 ]; then
  echo -n "Updating unsermake copy in $UNSERMAKE_PATH..."
  cd "$UNSERMAKE_PATH"
  svn up > /dev/null 2>&1
  echo $str_okay
fi

BASE_CONFIGUREFLAGS="$CONFIGUREFLAGS"
BASE_SUBDIR=$SUBDIR
BASE_CHECKOUT_PARTIAL="$CHECKOUT_PARTIAL"

for module in $modules; do
  module_variable SUBDIR
  SUBDIR=`echo $SUBDIR | sed -e "s,@MODULE@,$module,"`
  module_variable CHECKOUT_PARTIAL

  if [ -n "$KDELOGDIR" ]; then
    rm -f $KDELOGDIR/$module-build-*
    rm -f $KDELOGDIR/$module-failed-*
    rm -f $KDELOGDIR/$module-finished-*
    logfile="$KDELOGDIR/$module-build-$dateformat.log"
    echo "===============================================================================" > $logfile
    echo "Build log of module $module, started on `date +%c`" >> $logfile
    echo "===============================================================================" >> $logfile
    echo "" >> $logfile
  fi

  set_title "Updating module $module..."
  if [ "$dosvnupdate" -eq 0 ]; then
    echo -n "Checking module $module (no svn update)..."
    cmd_update_raw="echo Warning: no svn update of module $module - as requested"
  else
    if [ -n "$BRANCH" ]; then
      echo -n "Updating module $module ($BRANCH)..."
    else
      echo -n "Updating module $module ..."
    fi
    prepare_update
    cmd_update_raw="$cmd_update"
  fi

  log_section "Update $cmd_update"

  if [ "$dosvnupdate" -ne 0 -a -n "$CHECKOUT_PARTIAL" ]; then
    cmd_update_raw="$cmd_update -l $module"
  fi

  if test -d $KDESRCDIR/$module; then
    cd $KDESRCDIR/$module
  else 
    cd $KDESRCDIR 
  fi

  if ! log_cmd "$cmd_update_raw"; then
    echo "$str_error"
    continue
  fi
 
  if [ "$dosvnupdate" -ne 0 -a -n "$CHECKOUT_PARTIAL" ]; then
    prepare_update toponly
    echo "defined subdirs!"
    for part_dir in $CHECKOUT_PARTIAL; do
      echo -n "Updating subdirectory $part_dir"
      log_cmd "$cmd_update $module/$part_dir"
      echo " $str_okay"
    done
    echo -n "Final touch..."
  fi

  if [ "$CVS_CLEAN" = "yes" -a -e admin/Makefile.common -a "$INCREMENTAL_BUILD" != "yes" ]; then
    cmd_make_cvs_clean="$MAKE -f admin/Makefile.common cvs-clean"
  fi

  if ! log_cmd "$cmd_make_cvs_clean"; then
    echo "$str_error"
    continue
  fi

  if [ ! -e Makefile.cvs ]; then
    echo "$str_okay"
    continue
  fi

  if [ $domakecvs = 1 ] ; then
    make_makefile_cvs
  else
    echo "$src_okay"
    continue
  fi

  log_endsection "Updating"
done

# Now disconnect from the internet as we've finished updating
#
kppp_disconnect

for module in $modules; do
  module_variable CONFIGUREFLAGS

  # Nothing to do for kde-common
  [ "$module" = "kde-common" ] && continue
  logfile="$KDELOGDIR/$module-build-$dateformat.log"

  critical=0
  for m in $critical_modules; do if [ $m = $module ]; then critical=1; fi; done

  if ! cd $KDESRCDIR/$module; then
    if [ $critical -eq 1 ]; then
      echo "ERROR: Could not change into directory $KDESRCDIR/$module!"
      exit $err_change_into_mod_dir
    else
      echo "WARNING: Could not change into directory $KDESRCDIR/$module."
      echo "WARNING: Skipping module $module."
      continue
    fi
  fi

  # Check whether 'make -f Makefile.cvs' has been called.
  #
  if [ ! -e "Makefile.in" ]; then
    if [ $critical -eq 1 ]; then
      echo "ERROR: Please execute '$MAKE -f Makefile.cvs' first for module $module!"
      exit $err_no_makefile_in
    else
      echo "WARNING: '$MAKE -f Makefile.cvs' seems not to be executed for"
      echo "WARNING: module $module, skipping compilation."
      continue
    fi
  fi

  echo "Building module: $module"

  if [ -n "$KDEBUILDDIR" ]; then

    if [ "$BUILD_CLEAN" = "yes" -a "$INCREMENTAL_BUILD" != "yes" ]; then
      if [ -d $KDEBUILDDIR/$module ]; then
        echo -n "  Removing build dir..."
        set_title "Removing build dir for module $module..."
        rm -rf $KDEBUILDDIR/$module
        echo $str_okay
      fi
    fi
    mkdir -p $KDEBUILDDIR/$module
    cd $KDEBUILDDIR/$module
  fi

  # Configure the module.
  #
  echo -n "  Configuring..."
  set_title "Configuring module $module..."
  if [ -n "$KDEBUILDDIR" ]; then
    cmd_configure="$KDESRCDIR/$module/configure $CONFIGUREFLAGS --with-qt-dir=$QTDIR"
  else
    cmd_configure="./configure $CONFIGUREFLAGS --with-qt-dir=$QTDIR"
  fi
  if echo $CONFIGUREFLAGS | grep -v -- "--prefix=" 2>/dev/null >/dev/null; then
    cmd_configure="$cmd_configure --prefix=$KDEDIRS"
  fi
  [ "$NICECOMPILE" = yes ] && cmd_configure="nice $cmd_configure"
  configure_skipped=0
  if [ "$INCREMENTAL_BUILD" = "yes" -a -e "Makefile" ]; then
    cmd_configure_orig=$cmd_configure
    cmd_configure="echo Warning: no configure for module $module - as requested"
    configure_skipped=1
  fi
  log_section "Configuration"
  if [ -n "$KDELOGDIR" -a $configure_skipped -ne 1 ]; then
    echo $cmd_configure >> $logfile
  fi

  if ! log_cmd "$cmd_configure"; then
    echo "$str_error"
    move_logfile "failed"
    [ -n "$cmd_compress" ] && eval "$cmd_compress $logfile"
    [ $critical -eq 0 ] || exit $err_compile_fail
    continue
  fi

  log_endsection "Configuration"
  if [ $configure_skipped -eq 1 ]; then
    echo " skipped."
  else
    echo "$str_okay"
  fi

  if [ $configure_skipped -eq 1 ]; then
    echo -n "  Updating Makefile..."
    cmd_make_makefile="$MAKE $MAKE_OPTS Makefile"
    [ "$NICECOMPILE" = yes ] && cmd_make_makefile="nice $cmd_make_makefile"
    log_section "Updating Makefile"
    if [ -n "$KDELOGDIR" ]; then
      echo $cmd_make_makefile >> $logfile
    fi
    if ! log_cmd "$cmd_make_makefile"; then
      echo -n " Falling back to normal Makefile.cvs ..."
      worked=0

      if [ -n "$KDEBUILDDIR" ]; then
        cd $KDESRCDIR/$module # get back to the supermarket
      fi
      rm Makefile.in
      make_makefile_cvs
      if [ -n "$KDEBUILDDIR" ]; then
        cd $KDEBUILDDIR/$module # got the sugar, honey?
      fi
      echo -n "  Configuring..."
      if log_cmd "$cmd_configure_orig"; then
        if log_cmd "$cmd_make_makefile"; then
	    worked=1 
        fi
      fi
      if [ $worked -ne 1 ]; then
         echo "$str_error"
         move_logfile "failed"
         [ -n "$cmd_compress" ] && eval "$cmd_compress $logfile"
         [ $critical -eq 0 ] || exit $err_compile_fail
         continue
      fi
    fi

    log_endsection "Updating Makefile"
    echo "$str_okay"
  fi

  # Compile the module.
  #
  echo -n "  Compiling..."
  set_title "Compiling module $module..."
  use_compile_target=no
  [ -f $KDESRCDIR/$module/Makefile.am.in ] && [ -n "$MAKE_OPTS_COMPILE" ] && [ -n "$USE_UNSERMAKE" ] \
       && ! (echo $NO_UNSERMAKE_MODULES | grep $module > /dev/null 2>&1) \
       && use_compile_target=yes
  if [ "$use_compile_target" = yes ]; then
    cmd_make="$MAKE $MAKE_OPTS_COMPILE"
  else
    cmd_make="$MAKE $MAKE_OPTS"
  fi

  [ $critical -eq 0 ] && cmd_make="$cmd_make -k"
  [ "$NICECOMPILE" = yes ] && cmd_make="nice $cmd_make"
  [ "$use_compile_target" = yes ] && cmd_make="$cmd_make compile"

  log_section "Compilation $cmd_make"
  log_cmd "$cmd_make"
  retval=$?

  if [ $retval -eq 0 ]; then
    log_endsection "Compilation"
    echo "$str_okay"

    # Link the module
    if [ "$use_compile_target" = yes ]; then
      echo -n "  Linking..."
      set_title "Linking module $module..."
      cmd_make="$MAKE $MAKE_OPTS"
      [ $critical -eq 0 ] && cmd_make="$cmd_make -k"
      [ "$NICECOMPILE" = yes ] && cmd_make="nice $cmd_make"

      log_section "Linking $cmd_make"
      log_cmd "$cmd_make"
      retval=$?
      if [ $retval -eq 0 ]; then
        log_endsection "Linking"
        echo "$str_okay"
      fi
    fi
  fi

  if [ $retval -eq 0 ]; then
    # Install the module.
    #
    cmd_make_install="$MAKE $MAKE_OPTS"
    [ $critical -eq 0 ] && cmd_make_install="$cmd_make_install -k"
    [ "$NICECOMPILE" = yes ] && cmd_make_install="nice $cmd_make_install"
    cmd_make_install="$cmd_make_install install"
    if [ ! -w $KDEDIRS ]; then
      eval "$cmd_sudo \"$cmd_make_install\""
    else
      install_module
    fi
  else
   echo "$str_error"
    # Attempt to display the actual error
    grep -m1 -A2 ":[0-9]*: error:" $logfile
    move_logfile "failed"
    [ -n "$cmd_compress" ] && eval "$cmd_compress $logfile"
    [ $critical -eq 0 ] || exit $err_compile_fail
  fi
done

set_title "KDE build finished."

exit $err_no_error

=head1 NAME

kde-build - Updates and recompiles a tree of KDE modules

=head1 SYNOPSIS

        kde-build

=head1 DESCRIPTION

kde-build has been designed to keep a local copy of several KDE
modules up to date and recompile them. Those modules have to be saved in a
common directory, e.g. something like

    ~/kde-src/
      |
      +-> kdelibs/
      |
      +-> kdebase/
      |
      \-> kdenetwork/

In this case, the KDE source directory would be ~/kde-src/. The script will
take care of compiling them in the correct order, checks for dependencies
and resolves them as far as possible.

Please note that, prior to first invocation of the script, the configuration
file 'F<kde-buildrc>' has to be modified to reflect the local environment,
such as paths etc.

=head1 RETURN VALUE

The following error codes are returned by the script.

0 - No error seems to have occured.

1 - The script could not change into the directory of a module.

2 - The script could not open the file 'Makefile.in' of a module.

3 - The configuration of a module failed.

4 - The compilation of a module failed.

5 - The installation of a module failed.

6 - An invalid source directory was specified.

7 - An invalid Qt directory was specified.

11 - The configuration file F<kde-buildrc> couldn't be loaded.

12 - Both CVS_CLEAN and INCREMENTAL_BUILD were set

13 - Both BUILD_CLEAN and INCREMENTAL_BUILD were set

=head1 EXAMPLES

        cd ~/scripts/; vi ./kde-buildrc; ./kde-build

=head1 BUGS

Probably.

=head1 TODO

Add a DIAGNOSIS section to this man page.

=head1 AUTHOR

Frerich Raabe <raabe@kde.org>

=cut

# vim:et:ts=2:sw=2
