#!/bin/bash
#
# Copyright (C) 2005-2006 Falko Schmidt.
#
# 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 of the Software and its documentation and acknowledgment shall be
# given in the documentation and software packages that this Software was
# used.
# 
# 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 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.
# 
###############################################################################
#
# autoe version 0.1.0
# 
# A tool to build E17 Debian packages from CVS
#
# Author: Falko Schmidt <kaethorn@stud.uni-stuttgart.de>
#
# Features:
#  * Menudriven via dialog
#  * Only build the components which got updated
#  * Manage build order (add, remove, reorder)
#  * Error handling
#  * Resetting of date-stamps
#  * Batch mode either via menu or via invocation with --batch
#
# Requirements:
#  * Terminal
#  * dialog
#  * dpkg-dev
#  * devscripts
#  * cdbs
#  * sudo, fakeroot or root access
#  * generous amount of diskspace (around 1.5Gb)
#
# Recommended:
#  * debarchiver for managing the repository structure
#  * a script like egpg for passwordless pgp signatures
#
# Important:
# You need to specify a custom pgp command or shell script in order to
# to sign packages without password prompt (man gpg). To use it invoke
# it with the -p paramater of dpkg-buildpackage in the $DBUILDPACKAGE
# variable (e.g. "dpkg-buildpackage -psomescript"). Alternatively you
# can specify $DBUILDPACKAGE e.g as "dpkg-buildpackage -uc -us" to not
# sign packages and sources at all.

# TODO:
#  * Finetune e_replace to reset only updated components
#  * Function to correct version number in changelog(.in) after checkout

#########################
# Configuration options #
#########################

# some helpful environmental variables
export MAKE="make -j3"

# Define the working directory. This is used for storing the CVS tree
# and packages prior to moving them (if $AUTOMOVE=0 then packages will
# stay here).
WORKDIR=/usr/src/e

# Flag to automatically install packages after building them. This
# might be necessary to fulfill build requirements for later 
# packages. It's recommended to leave it enabled.
AUTOINSTALL=1

# Flag to automatically move packages to $MOVEDIR after installation.
# It's recommended to leave it enabled and to set a proper $MOVEDIR
AUTOMOVE=1

# Flag to reset date after checkout.
# This is recommended if your debian/changelog files have a date stamp of 
# form 'date +%Y%m%d' (can be specified below).
DATERESET=1

# Format of the date string used in debian/changelog files
DATEFORMAT="%Y%m%d"

# Directory to move packages to, optionally every time a package builds 
# successfully - see $AUTOMOVE.
MOVEDIR="/var/lib/debarchiver/incoming/unstable/"

# List of scripts that can be executed from the menu.
CUSTSCRIPTS="/usr/local/bin/edebarchiver.sh"

# Maintainer string for entry in debian/changelog
MAINTAINERADDRESS="Falko Schmidt <kaethorn@stud.uni-stuttgart.de>"

# define the dpkg-buildpackage command line
DBUILDPACKAGE="dpkg-buildpackage -pegpg"

# Flag to control whether to replace the Maintainer string in debian/control.
# This doesn't need to be touched usually.
REPLACE_CONTROL_MAINTAINER=0

# Packages which don't build (yet)
DONTBUILDLIST="e17/apps/euphoria e17/proto/exorcist misc/enthrall e17/proto/etk-perl e17/proto/ruby-efl misc/devs"

# List of scripts that will be run after BatchRun finished creating
# debs.
BATCHCOMMANDS="/usr/local/bin/edebarchiver.sh"

# Set this variable to 0 once all options are configured.
NOTCONFIGURED="0"



################################
# Don't edit beyond this point #
################################

# Set the date
DATE=`date +$DATEFORMAT`

# The build list
ULIST=""

# List of addable items
ALIST=""

# Parse command line for batch more
if [[ "$1" = "-b" ]];then
   e_checkout
   e_checkupdates "batch"
   e_build
   e_runbatchcommands
elif [[ "$1" = "--batch" ]];then
   e_checkout
   e_checkupdates "batch"
   e_build
   e_runbatchcommands
fi

#-------------------------------------------------------------------#
# function which prints the help                                    #
#-------------------------------------------------------------------#
function e_printhelp {

   dialog --title "autoe - help" --clear \
          --msgbox " \
\n\
Welcome to autoe. This script is made for maintaining the\n \
E17 Debian repository at edevelop.org/debian. It might as\n \
well work for other source trees with some adjustments.\n \
\n\
Before using this script you should really make sure to\n \
edit this file and adjust the settings accordingly.\n \
\n\
The following lines describe the main menu option:\n\
\n\
* BatchRun     - This option runs of the following commands: \n \
                 * Update \n \
                 * CheckUpdates \n \
                 * Build \n \
                 * user defined commands (see '\$BATCHCOMMANDS') \n \
               These routines are automatically executed if \n \
               autoe is invoked with --batch or -b \n \
 \n \
* Update       - Checks out the CVS repository. \n \
 \n \
* CheckUpdates - Scan for items which have been updated \n \
                 during the checkout. Overrides the previous \n \
                 build list. \n \
 \n \
* ViewList     - Display the current build list. \n \
 \n \
* ReorderList  - Reorder items on the build list. \n \
 \n \
* RemoveItem   - Remove items from the build list. \n \
 \n \
* AddItem      - Manually add items to the build list. \n \
 \n \
* Build        - Build the items on the build list. \n \
 \n \
* Help         - Print this help text. \n \
 \n \
* Install      - Installs all Debian packages found. \n \
 \n \
* Move         - Moves .deb, .dsc, .changes and .tar.gz \n \
                 files (the latter only if applicable) \n \
                 to '\$MOVEDIR' \n \
 \n \
* Custom       - Prompt for running external scripts which \n \
                 can be specified with the '\$CUSTSCRIPTS' \n \
                 variable. \n \
 \n \
* Quit         - Quit autoe. The original build list can be \n \
                 recovered by choosing 'CheckUpdates' the \n \
                 next time you run autoe. \n \
 \n " 20 72
}

#-------------------------------------------------------------------#
# function which prints the list of remaining build jobs            #
#-------------------------------------------------------------------#
function e_printlist {
   
  if [[ $ULIST = "" ]]
  then
	  dialog --title "autoe - no build jobs" --clear \
	  --msgbox "The build queue is empty. Please make sure to check for updates before." 6 42
	  return
  fi

  COUNTER=1
  echo "" > /tmp/autoe-listtmp
  for e in $ULIST
  do
     echo "   "$COUNTER") "$e >> /tmp/autoe-listtmp
     let COUNTER=$COUNTER+1
  done
  dialog --title "autoe - current build jobs" --clear \
  --textbox /tmp/autoe-listtmp 18 46
  rm /tmp/autoe-listtmp
   
}

#-------------------------------------------------------------------#
# function to replace date stamps and adjust maintainer entries     #
#-------------------------------------------------------------------#
function e_replace {

   cd $1

   for file in $(find -name 'changelog*')
   do 
      # add cvs+date stamp
      sed -e 's/(\([0-9]\(\.[0-9]\+\)\+\)\-1)/(\1\-0cvs'$DATE')/g' $file > 58239
      cat 58239 > $file
      sed -e 's/(\(\@VERSION\@\)\-1)/(\1\-0cvs'$DATE')/g' $file > 58239
      cat 58239 > $file
      sed -e 's/(\([0-9]\(\.[0-9]\+\)\+\))/(\1\-0cvs'$DATE')/g' $file > 58239
      cat 58239 > $file
      sed -e 's/(\(\@VERSION\@\))/(\1\-0cvs'$DATE')/g' $file > 58239
      cat 58239 > $file

      # adjust date
      sed -e 's/cvs[0-9]*/cvs'$DATE'/g' $file > 58239
      cat 58239 > $file

      if [ $REPLACE_CONTROL_MAINTAINER = "1" ]
      then
         # adjust maintainer
         sed -e 's/\-\-\ .*/\-\-\ Falko Schmidt \<kaethorn\@stud\.uni\-stuttgart\.de\>\ \ Tue\,\ 7\ Mar\ 2006\ 13\:30\:15\ \+0000/g' $file > 58239
         cat 58239 > $file
      fi

   done


   if [ $REPLACE_CONTROL_MAINTAINER = "1" ]
   then
      for file in $(find -name 'control')
      do

         sed -e 's/Maintainer.*/Maintainer\: Falko Schmidt \<kaethorn\@stud\.uni\-stuttgart\.de\>/g' $file > 58239
         cat 58239 > $file
  
      done
   fi

   rm -f 58239
   cd ..

}

#-------------------------------------------------------------------#
# function which checks out the E17 CVS repository                  #
#-------------------------------------------------------------------#
function e_checkout {

   # Set the date again, in case this script runs nonstop.
   DATE=`date +$DATEFORMAT`
   
   (
   if [ "$DATERESET" = "1" ]
   then
	   echo "XXX"
	   echo "0"
	   echo "\n checking out the e17 branch"
	   echo "XXX"
   	   cvs -z3 -d :pserver:anonymous@anoncvs.enlightenment.org:/var/cvs/e checkout -P e17 &> e17-log-co
	   
	   echo "XXX"
	   echo "16"
	   echo "\n checking out the e_modules branch"
	   echo "XXX"
   	   cvs -z3 -d :pserver:anonymous@anoncvs.enlightenment.org:/var/cvs/e checkout -P e_modules &> e_modules-log-co
	   
	   echo "XXX"
	   echo "33"
	   echo "\n checking out the misc branch"
	   echo "XXX"
   	   cvs -z3 -d :pserver:anonymous@anoncvs.enlightenment.org:/var/cvs/e checkout -P misc &> misc-log-co
	   
	   echo "XXX"
	   echo "50"
   else
	   echo "XXX"
	   echo "0"
	   echo "\n checking out the e17 branch"
	   echo "XXX"
   	   cvs -z3 -d :pserver:anonymous@anoncvs.enlightenment.org:/var/cvs/e checkout -P e17 &> e17-log-co
	   
	   echo "XXX"
	   echo "33"
	   echo "\n checking out the e_modules branch"
	   echo "XXX"
   	   cvs -z3 -d :pserver:anonymous@anoncvs.enlightenment.org:/var/cvs/e checkout -P e_modules &> e_modules-log-co
	   
	   echo "XXX"
	   echo "66"
	   echo "\n checking out the misc branch"
	   echo "XXX"
   	   cvs -z3 -d :pserver:anonymous@anoncvs.enlightenment.org:/var/cvs/e checkout -P misc &> misc-log-co
	   
	   echo "XXX"
	   echo "99"
	   echo "\n done."
	   echo "XXX"
   fi
	   
   if [ "$DATERESET" = "1" ]
   then
	   echo "\n resetting the date for e17 branch"
	   echo "XXX"
	   e_replace e17

	   echo "XXX"
	   echo "66"
	   echo "\n resetting the date for misc branch"
	   echo "XXX"
	   e_replace misc

	   echo "XXX"
	   echo "83"
	   echo "\n resetting the date for e_modules branch"
	   echo "XXX"
	   e_replace e_modules

	   echo "XXX"
	   echo "99"
	   echo "\n done."
	   echo "XXX"
   fi

   ) |

   dialog --title "autoe - CVS checkout progress" --gauge "" 8 70 0

   cat e_modules-log-co >> e17-log-co
   rm e_modules-log-co
   cat misc-log-co >> e17-log-co
   rm misc-log-co
   
   # FIXME: this is a dirty hack and should be fixed upstream
   rm -Rf e_modules/calendar e_modules/engage

   # dpkg-buildpackage needs all rules files to be executable
   find -name 'rules' -exec chmod +x {} \;

}

#-------------------------------------------------------------------#
# function which generates a list of updates elements so that       #
# only those are being built later                                  #
#-------------------------------------------------------------------#
function e_checkupdates {
   
   #(

   # Libs
   LILIST="$(grep -e U\ e17\/libs\/ e17-log-co | sed -e 's/U\ e17\/libs\///g' | sed -e 's/\/.*//g' | uniq | sed -e 's/.*/e17\/libs\/&/g')"

   # Apps
   APLIST="$(grep -e U\ e17\/apps\/ e17-log-co | sed -e 's/U\ e17\/apps\///g' | sed -e 's/\/.*//g' | uniq | sed -e 's/.*/e17\/apps\/&/g')"

   # Proto
   PRLIST="$(grep -e U\ e17\/proto\/ e17-log-co | sed -e 's/U\ e17\/proto\///g' | sed -e 's/\/.*//g' | uniq | sed -e 's/.*/e17\/proto\/&/g')"

   # Misc
   MILIST="$(grep -e U\ misc\/ e17-log-co | sed -e 's/U\ misc\///g' | sed -e 's/\/.*//g' | uniq | sed -e 's/.*/misc\/&/g')"

   # e-modules
   MOLIST="$(grep -e U\ e_modules\/ e17-log-co | sed -e 's/U\ //g' | sed -e 's/\/.*//g' | uniq)"

   TLIST="$LILIST $APLIST $PRLIST $MILIST $MOLIST"

   if [[ $1 != "batch" ]]
   then
      if [[ $TLIST = "    " ]]
      then
           $TLIST=""
           dialog --title "autoe - no updates found" --clear \
           --yesno \
           "No updates found or CVS error.\nDo you want to view the log file?" 6 40
           case $? in
              0)
              dialog --clear --title "autoe - checkout log file" \
              --textbox e17-log-co 20 75;;
              1)
              echo "no chosen";;
              255)
              exit;;
           esac
      else
           echo "" >> /tmp/autoe-listtmp
           echo "The following updates to the source trunk have been found." >> /tmp/autoe-listtmp
           echo "Unlike the resulting build queue this list is neither sorted" >> /tmp/autoe-listtmp
           echo "nor stripped of items which are not meant to be built." >> /tmp/autoe-listtmp
           echo "Existing build jobs will be merged." >> /tmp/autoe-listtmp
           echo "" >> /tmp/autoe-listtmp
           COUNTER=1
           for e in $TLIST
      	do
      	   echo "   "$COUNTER") "$e >> /tmp/autoe-listtmp
              let COUNTER=$COUNTER+1
      	done
           dialog --title "autoe - updates found" --clear \
           --textbox /tmp/autoe-listtmp 20 75
           rm /tmp/autoe-listtmp
      fi
   fi
   
   # merge current build queue with new updates:
   ULIST="$ULIST $TLIST"
     
   for item in $ULIST
   do
	   echo $item >> /tmp/autoe-listtemp2
   done

   ULIST="$(cat /tmp/autoe-listtemp2|sort|uniq)"

   # remove items from the $DONTBUILDLIST
   for item in $DONTBUILDLIST
   do
   	ULIST="${ULIST/$item/}"
   done
   rm /tmp/autoe-listtemp2
   
   e_sort
   
}

#-------------------------------------------------------------------#
# function which build selected elements of the source tree         #
#-------------------------------------------------------------------#

function e_build {
   
   if [[ $ULIST = "" ]]
   then
	dialog --title "autoe - empty queue" --clear \
	--msgbox \
	"The build queue is empty.\nPlease make sure to check the trunk." 6 40
	case $? in
	   0)
	   return;;
	   255)
	   return;;
	esac
   fi
   
   # how many build jobs?
   AMOUNT=0
   for i in $ULIST
   do
	   let AMOUNT=$AMOUNT+1
   done

   # we need steps for configuring, building and installing
   let AMOUNT=$AMOUNT*3

   # remember the parent dir
   PD=$(pwd)
   
   COUNTER=0
   (
   for job in $ULIST
   do

	   echo "XXX"
	   PCT=`expr \( \( 100 \/ $AMOUNT  \) \* $COUNTER \)`
	   echo $PCT
	   echo "\n  configuring $job ..."
	   echo "XXX"
	   ######################################
	   # run autogen.sh and configure
	   ######################################
	   cd $job
           
	   # exception for ecore:
           if [ "$job" = "e17/libs/ecore" ]
           then
              ./autogen.sh --prefix=/usr --disable-ecore-evas-dfb \
              			     --disable-ecore-dfb \
            			     --enable-ecore-fb \
            			     --enable-ecore-evas-fb &> /tmp/autoe-conf-log
              RC=$?
           # exception for evas:
           elif [ "$job" = "e17/libs/evas" ]
           then
              ./autogen.sh --prefix=/usr --enable-gl-x11 &> /tmp/autoe-conf-log
              RC=$?
           else
              ./autogen.sh --prefix=/usr &> /tmp/autoe-conf-log
              RC=$?
           fi
           # check the return code
           if [ "$RC" -ne 0 ]
           then
		   echo "config" > /tmp/autoe-rs
		   echo "$job" > /tmp/autoe-rsi
		   return
	   fi
	   let COUNTER=$COUNTER+1
	   ######################################
           
	   echo "XXX"
	   PCT=`expr \( \( 100 \/ $AMOUNT  \) \* $COUNTER \) \+ 1`
	   echo $PCT
	   echo "\n  compiling $job ..."
	   echo "XXX"
	   ######################################
           # build the package
	   ######################################
           $DBUILDPACKAGE -m"$MAINTAINERADDRESS" -e"$MAINTAINERADDRESS" &> /tmp/autoe-build-log
           RC=$?
           # check the return code
           if [ "$RC" -ne 0 ]
           then
		   echo "compile" > /tmp/autoe-rs
		   echo "$job" > /tmp/autoe-rsi
		   return
           fi

	   # remove the successfully built item from the list
           ULIST="${ULIST/$job/}"
           rm -f /tmp/autoe-ulist
           for item in $ULIST
           do
                   echo $item >> /tmp/autoe-ulist
           done

	   let COUNTER=$COUNTER+1
	   ######################################
           
	   echo "XXX"
	   PCT=`expr \( \( 100 \/ $AMOUNT  \) \* $COUNTER \)`
	   echo $PCT
	   echo "\n  installing $job ..."
	   echo "XXX"
	   sleep 1
	   ######################################
           # install packages if wanted by user
	   ######################################
           if [[ $AUTOINSTALL = 1 ]]
           then
           if [[ $( echo $DONTBUILDLIST | grep $job" " | wc -c ) = 0 ]]
           then
              cd ..
              dpkg -i *.deb &> /tmp/autoe-install-log
              RC=$?
              if [ $RC -ne 0 ]
              then
		   echo "install" > /tmp/autoe-rs
		   echo "$job" > /tmp/autoe-rsi
		   return
              fi
              
              # move packages if wanted by user
              if [[ $AUTOMOVE = 1 ]]
              then
                 # check whether we build source files tarballs
                 if [[ $( echo $DBUILDPACKAGE | grep '\ \-b' | wc -c) > 0 ]]
                 then
                    mv *.deb *.changes $MOVEDIR
                 else   
                    mv *.deb *.tar.gz *.changes *.dsc $MOVEDIR
                 fi
              fi
           fi
           fi
           # return to parent dir
           cd $PD
	   ######################################


	   let COUNTER=$COUNTER+1

   done
   echo XXX
   echo "100"
   echo "\n Done."
   echo "XXX"
   sleep 1
   echo "ok" > /tmp/autoe-rs
   ) |
   dialog --title "autoe - build progress" --gauge "" 8 60 0

   STAGE=`cat /tmp/autoe-rs`
   rm -f /tmp/autoe-rs
   COMPILE_FAILED=0

   if [[ $STAGE = "config" ]]
   then
      JOB=`cat /tmp/autoe-rsi`
      rm -f /tmp/autoe-rsi
      COMPILE_FAILED=1
      dialog --title "autoe - configure error" --yesno "Something went wrong while running autogen.sh and configure for $JOB.\nDo you want to view the log file?" 0 0
      case $? in
         0)
         dialog --clear --title "autoe - checkout log file" \
         --textbox /tmp/autoe-conf-log 20 75;;
         1)
         cd $PD
         return;;
         255)
         cd $PD
         return;;
      esac
      dialog --title "autoe - continue?" --clear \
      --msgbox "Will drop back to the main menu.\nPlease run 'Build' again once the issue is fixed." 6 55
      cd $PD
      return
   elif [[ $STAGE = "compile" ]]
   then
      JOB=`cat /tmp/autoe-rsi`
      rm -f /tmp/autoe-rsi
      COMPILE_FAILED=1
      dialog --title "autoe - build error" --clear \
      --yesno "Something went wrong while compiling and packaging $JOB.\nDo you want to view the log file?" 6 50
      case $? in
         0)
         dialog --clear --title "autoe - build log file" \
         --textbox /tmp/autoe-build-log 20 75;;
         1)
         cd $PD
	 return;;
	 255)
         cd $PD
	 return;;
      esac
      dialog --title "autoe - continue?" --clear \
      --msgbox "Will drop back to the main menu.\nPlease run 'Build' again once the issue is fixed." 6 55
      cd $PD
      return
   elif [[ $STAGE = "install" ]]
   then
      JOB=`cat /tmp/autoe-rsi`
      rm -f /tmp/autoe-rsi
      COMPILE_FAILED=1
      dialog --title "autoe - install error" --clear \
      --yesno "Something went wrong while installing the package $JOB.\nDo you want to view the log file?" 6 50
      case $? in
         0)
         dialog --clear --title "autoe - install log file" \
         --textbox /tmp/autoe-install-log 20 75;;
         1)
         cd $PD
         return;;
         255)
         cd $PD
         return;;
      esac
      dialog --title "autoe - continue?" --clear \
      --msgbox "Will drop back to the main menu.\nPlease run 'Build' again once the issue is fixed." 6 55
      cd $PD
      return
   else
      ULIST="$(cat /tmp/autoe-ulist|sort|uniq)"
   fi

   rm -f /tmp/autoe-ulist

}

#-------------------------------------------------------------------#
# function which adds an item to the list of build jobs             #
#-------------------------------------------------------------------#
function e_add {

   # create a list of all available source trees - if not yet done
   if [[ $ALIST = "" ]]
   then
      dialog --sleep 30 --title "autoe - please wait" \
--infobox "A list of all available packages is being generated." 3 56 &
      # Libs
      LILIST="$(find e17/libs -type d | sed -e 's/e17\/libs\///g' |  sed -e 's/\/.*//g'|uniq|grep -v CVS|grep -v e17 |sed -e 's/.*/e17\/libs\/&/g')"
      # Apps
      APLIST="$(find e17/apps -type d | sed -e 's/e17\/apps\///g' |  sed -e 's/\/.*//g'|uniq|grep -v CVS|grep -v e17 |sed -e 's/.*/e17\/apps\/&/g')"
      # Proto
      PRLIST="$(find e17/proto -type d | sed -e 's/e17\/proto\///g' |  sed -e 's/\/.*//g'|uniq|grep -v CVS|grep -v e17 |sed -e 's/.*/e17\/proto\/&/g')"
      # Misc
      MILIST="$(find misc -type d | sed -e 's/misc\///g' |  sed -e 's/\/.*//g'|uniq|grep -v CVS|grep -v misc |sed -e 's/.*/misc\/&/g')"
      # e-modules
      MOLIST="e_modules"
           	        
      ALIST="$LILIST $APLIST $PRLIST $MILIST $MOLIST"
   fi
  
   dialog --title "autoe - add build jobs" \
          --checklist "Choose all the items which should be added to the\nbuild queue.\n" 20 61 10 \
        `for i in $ALIST;do echo $i" . \n ";done` \
	2> /tmp/autoe-addchoice

   ULIST=$ULIST" "`cat /tmp/autoe-addchoice |sed -e 's/\"//g'`

   e_sort

   rm -f /tmp/autoe-addchoice
}

#-------------------------------------------------------------------#
# function which sorts the queue to reflect e17 build order         #
#-------------------------------------------------------------------#
function e_sort {

   # only libs need order
   LLIST=`echo $ULIST | sed -e 's/e17\/apps\/[-0-9_A-Z.a-z]*//g' | sed -e 's/e_modules//g' | sed -e 's/e17\/proto\/[-0-9_A-Z.a-z]*//g' | sed -e 's/misc\/[-0-9_A-Z.a-z]*//g' | sed -e 's/e17\/libs\/CVS//g' | sed -e 's/e17\/libs\/e17//g'`
   # the rest
   RLIST=`echo $ULIST | sed -e 's/e17\/libs\/[-0-9_A-Z.a-z]*//g'`
   
   # the build order is defined in OLIST. now delete every item in OLIST
   # which is not in LLIST, thus OLIST contains all relevant items. then
   # delete every item in LLIST which is in the resulted OLIST to obtain
   # a list of non-relevant items in LLIST.
   OLIST="e17/libs/eet e17/libs/edb e17/libs/evas e17/libs/ecore e17/libs/embryo e17/libs/imlib2 e17/libs/edje e17/libs/epeg e17/libs/epsilon e17/libs/esmart e17/libs/emotion e17/libs/engrave e17/libs/ewl e17/proto/etk"
   for i in $OLIST
   do
	   if [[ `echo $LLIST|grep $i|wc -c` = 0 ]]
	   then
		   OLIST="${OLIST/$i/}"
	   fi
   done
   for i in $LLIST
   do
	   if [[ `echo $OLIST|grep $i|wc -c` > 0 ]]
	   then
		   LLIST="${LLIST/$i/}"
	   fi
   done

   # if etk is in the rest list, then delete if from there and add it
   # to the library list:
   if [[ `echo $RLIST | grep proto\/etk | wc -c` > 0 ]]
   then
	   RLIST="${RLIST/e17\/proto\/etk/}"
	   LLIST=$LLIST" e17/proto/etk"
   fi

   # this list contains all libraries - sorted
   LLIST="$OLIST $LLIST"

   # put them back together
   ULIST="$LLIST $RLIST"

}

#-------------------------------------------------------------------#
# function which removes items from the list of build jobs          #
#-------------------------------------------------------------------#
function e_remove {

   if [[ $ULIST = "" ]]
   then
	dialog --title "autoe - empty queue" --clear \
	--msgbox \
	"The build queue is empty.\nPlease make sure to check the trunk." 6 40
	case $? in
	   0)
	   return;;
	   255)
	   return;;
	esac
   fi

   dialog --title "autoe - delete build jobs" \
          --checklist "Check all the items which should be \n\
deleted from the build queue.\n" 20 61 10 \
        `for i in $ULIST;do echo $i" . \n ";done` \
	2> /tmp/autoe-delchoice

   DLIST=`cat /tmp/autoe-delchoice |sed -e 's/\"//g'`
   for i in $DLIST
   do
	   ULIST=${ULIST/$i/}
   done

   rm -f /tmp/autoe-delchoice
   
}

#-------------------------------------------------------------------#
# function which manages shuffling items in the build list          #
#-------------------------------------------------------------------#
function e_reorder {
   
   if [[ $ULIST = "" ]]
   then
	dialog --title "autoe - empty queue" --clear \
	--msgbox \
	"The build queue is empty.\nPlease make sure to check the trunk." 6 40
	case $? in
	   0)
	   return;;
	   255)
	   return;;
	esac
   fi

   dialog --title "autoe - reorder build jobs" \
          --radiolist "Choose the item which should be\n\
reordered in the build queue.\n" 20 61 10 \
        `for i in $ULIST;do echo $i" . \n ";done` \
	2> /tmp/autoe-reochoice

   RCHOICE=`cat /tmp/autoe-reochoice |sed -e 's/\"//g'`
   rm -f /tmp/autoe-reochoice

   if [[ "$RCHOICE" = "" ]]
   then
	dialog --title "autoe - error" --clear \
	--msgbox \
	"No item chosen, use the space key to select." 5 50
	case $? in
	   0)
	   e_reorder;;
	   255)
	   e_reorder;;
	esac
   fi
   
   e_place "$RCHOICE"
   e_printlist

}

#-------------------------------------------------------------------#
# function which places an build list item in front of another      #
#-------------------------------------------------------------------#
function e_place {
   
   dialog --title "autoe - reorder build jobs" \
          --radiolist "Choose an item where "$1"\n\
should be placed in front of.\n" 20 61 10 \
        `for i in $ULIST;do echo $i" . \n ";done` \
	2> /tmp/autoe-tarchoice
   
   TCHOICE=`cat /tmp/autoe-tarchoice |sed -e 's/\"//g'|sed -e 's/.$//g'`
   rm -f /tmp/autoe-tarchoice
   
   if [[ "$TCHOICE" = "" ]]
   then
	dialog --title "autoe - error" --clear \
	--msgbox \
	"No item chosen, use the space key to select." 5 50
	case $? in
	   0)
	   e_place $1;;
	   255)
	   e_place $1;;
	esac
   fi
  
   if [[ "$TCHOICE" = "$1" ]]
   then
	dialog --title "autoe - error" --clear \
	--msgbox \
	"Can't place an item in front of itself." 5 45
	case $? in
	   0)
	   return;;
	   255)
	   return;;
	esac
   elif [ `echo $ULIST | grep "$TCHOICE" | wc -c` > 0 ]
   then
   	ULIST="${ULIST/$1/}"
	SUBSTR=$1" "$TCHOICE
	ULIST="${ULIST/$TCHOICE/$SUBSTR}"
	return
   else
	dialog --title "autoe - error" --clear \
	--msgbox \
	"Bad option or bug in this script." 5 42
	case $? in
	   0)
	   return;;
	   255)
	   return;;
	esac
   fi

}

#-------------------------------------------------------------------#
# function which calls scripts defined by the user                  #
#-------------------------------------------------------------------#
function e_custom {
  
   COUNTER=0
   for i in $CUSTSCRIPTS
   do
	   let COUNTER=$COUNTER+1
   done
   if [[ $COUNTER = 0 ]]
   then
	   dialog --title "autoe - no commands found" --clear \
	          --msgbox "No commands were defined." 5 40
		  return
   fi

   dialog --title "autoe - custom applications" \
          --checklist "Choose commands which should be executed. The \nrunning order is defined by the item's position.\n" 20 61 10 \
        `for i in $CUSTSCRIPTS;do echo $i" . \n ";done` \
	2> /tmp/autoe-comchoice

   CCHOICE=`cat /tmp/autoe-comchoice |sed -e 's/\"//g'`
   for item in $CCHOICE
   do
           dialog --sleep 30 --title "autoe - please wait" \
           --infobox "Running "$item" ..." 3 50 &
	   sh $item &> /tmp/autoe-exe-log
           RC=$?
           if [ $RC -ne 0 ]
           then
	      dialog --title "autoe - execution error" --clear \
	      --yesno \
	      "Something went wrong while executing the file $item.\nDo you want to view the log file?" 6 50
	      case $? in
	         0)
	         dialog --clear --title "autoe - execution log file" \
	         --textbox /tmp/autoe-exe-log 20 75
		 rm -f /tmp/autoe-exe-log;;
	         1)
	         return;;
	         255)
	         return;;
	      esac
	      dialog --title "autoe - continue?" --clear \
	      --msgbox "Will drop back to the main menu.\nPlease run 'Custom' again once the issue is fixed." 6 55
	      return
           fi
   done

}

#-------------------------------------------------------------------#
# function which installs all packages in e17/, misc/ & e_modules   #
#-------------------------------------------------------------------#
function e_install {
   
   DLIST=$(find e17 misc e_modules -name '*.deb' | sed -e 's/\n/\ /g' )

   AMOUNT=0
   for file in $DLIST
   do
	   let AMOUNT=$AMOUNT+1
   done
   
   if [[ $AMOUNT = 0 ]]
   then
	   dialog --title "autoe - no packages found" --clear \
	   --msgbox "No Debian packages found! Nothing to do." 5 44
	   return
   fi

   COUNTER=0
   (
   for file in $DLIST
   do
	   echo "XXX"
	   PCT=`expr \( \( 100 \/ $AMOUNT  \) \* $COUNTER \)`
	   echo $PCT
	   echo "  installing "$file" ..."
	   echo "XXX"
	   dpkg -i $file &> /tmp/autoe-install-log
           RC=$?
           if [ $RC -ne 0 ]
           then
		   echo "install" > /tmp/autoe-rs
		   return
           fi
              
	   let COUNTER=$COUNTER+1
   done
   echo "ok" > /tmp/autoe-rs
   ) |
   dialog --title "autoe - install progress" --gauge "" 8 60 0

   STAGE=`cat /tmp/autoe-rs`
   rm -f /tmp/autoe-rs
   
   if [[ $STAGE = "install" ]]
   then
      dialog --title "autoe - install error" --clear \
      --yesno "Something went wrong while installing the package $file.\nDo you want to view the log file?" 6 50
      case $? in
         0)
         dialog --clear --title "autoe - install log file" \
         --textbox /tmp/autoe-install-log 20 75
	 rm -f /tmp/autoe-install-log;;
         1)
         return;;
         255)
         return;;
      esac
      dialog --title "autoe - continue?" --clear \
      --msgbox "Will drop back to the main menu.\nPlease run 'Install' again once the issue is fixed." 6 55
      return
   fi
   
}

#-------------------------------------------------------------------#
# function which moves all repository relevant files to $MOVEDIR    #
#-------------------------------------------------------------------#
function e_move {
   
   find e17 misc e_modules -name '*.deb' -exec mv {} $MOVEDIR \;
   find e17 misc e_modules -name '*.changes' -exec mv {} $MOVEDIR \;  
   # check whether we build source files tarballs
   if [[ $( echo $DBUILDPACKAGE | grep '\-b' | wc -c) = 0 ]]
   then
      find e17 misc e_modules -name '*.tar.gz' -exec mv {} $MOVEDIR \;
      find e17 misc e_modules -name '*.dsc' -exec mv {} $MOVEDIR \;
      dialog --title "autoe - finished moving files" --clear \
      --msgbox "All files ending in either .deb, .changes .tar.gz or .dsc have been moved to $MOVEDIR. Please verify manually." 7 60
   else
      dialog --title "autoe - finished moving files" --clear \
      --msgbox "All files ending in either .deb or .changes have been moved to $MOVEDIR. Please verify manually." 7 60
   fi
   
}

#-------------------------------------------------------------------#
# function which calls scripts after BatchRun has finished          #
#-------------------------------------------------------------------#
function e_runbatchcommands {

   COUNTER=0
   for command in $BATCHCOMMANDS
   do
           let COUNTER=$COUNTER+1
   done
   if [[ $COUNTER = 0 ]]
   then
           dialog --title "autoe - no commands found" --clear \
           --msgbox "No additional batch commands were specified. Done." 5 44
           return
   fi
   if [[ $COMPILE_FAILED = 1 ]]
   then
           return
   fi

   for command in $BATCHCOMMANDS
   do
           dialog --sleep 30 --title "autoe - please wait" \
           --infobox "Running "$command" ..." 3 50 &
           sh $command &> /tmp/autoe-exe-log
           RC=$?
           if [ $RC -ne 0 ]
           then 
              dialog --title "autoe - execution error" --clear \
              --yesno \
              "Something went wrong while executing the file $command.\nDo you want to view the log file?" 6 50
	      case $? in
                 0)
                 dialog --clear --title "autoe - execution log file" \
                 --textbox /tmp/autoe-exe-log 20 75
                 rm -f /tmp/autoe-exe-log;;
                 1) 
                 return;;
                 255)
                 return;;
              esac
              dialog --title "autoe - continue?" --clear \
              --msgbox "Will drop back to the main menu.\nPlease run 'Batch Run' again once the issue is fixed." 6 55                                                         return
           fi 
   done    

   dialog --title "autoe - finished" --clear \
   --msgbox "Finished running all batch jobs." 5 40

}

#-------------------------------------------------------------------#
# function which checks whether variables are set correctly         #
#-------------------------------------------------------------------#
function e_checkenv {

   if [[ $NOTCONFIGURED = "1" ]]
   then
      echo ""
      echo "   autoe is not configured properly. Please edit this script"
      echo "   and adjust the necessary options."
      echo ""
      exit 1
   fi
   
   if [[ $1 = "--batch" ]] | [[ $1 = "-b" ]]
   then
      e_checkout
      e_checkupdates "batch"
      e_build
      e_runbatchcommands
      exit 0
   fi
      
   for e in $CUSTSCRIPTS
   do
      if [ ! -e $e ] | [ ! -x $e ]
      then
         echo ""
	 echo "   Warning! The script "$e "was specified but"
	 echo "   \$CUSTSCRIPTS doesn't exist or is not executable."
	 echo ""
      fi
   done

   for e in $BATCHCOMMANDS
   do
      if [ ! -e $e ] | [ ! -x $e ]
      then
         echo ""
	 echo "   Warning! The script "$e "was specified but"
	 echo "   in \$BATCHCOMMANDS doesn't exist or is not executable."
	 echo ""
      fi
   done


   if [ ! -d $MOVEDIR ] && [ "$AUTOINSTALL" = "1" ]
   then
      echo ""
      echo "   Warning! Directory "$MOVEDIR "doesn't exist"
      echo "   (or is a file). Please provide a directory where"
      echo "   packages can be moved to by setting the \$MOVEDIR"
      echo "   variable."
      echo ""
      exit 1
   fi

   if [ ! -d $WORKDIR ]
   then
      echo ""
      echo "   Warning! Directory "$WORKDIR "doesn't exist"
      echo "   (or is a file). Please provide a directory where"
      echo "   this script should be operating in."
      echo ""
      exit 1
   fi

}

#-------------------------------------------------------------------#
# main                                                              #
#-------------------------------------------------------------------#

# check the settings and manage command line options
e_checkenv

cd $WORKDIR

while $TRUE
do
   dialog --clear --item-help --title "autoe - main menu" \
          --menu "This program is used to maintain the Debian E17 repository at edevelop.org. See 'Help' for details.\n" 20 70 12 \
   	       "Batch Run"  "Runs 'Update trunk', 'Check trunk' and 'Build'" "afterwards custom commands will be executed, see 'Help'." \
   	       "Update trunk"  "Checks out the source tree from CVS" "" \
   	       "Check trunk"  "Finds packages which needs to be rebuild" "only updated source trees will be selected to cut down build time." \
   	       "View list"   "Lists the current build queue" "don't forget to choose 'check trunk' before." \
   	       "Reorder list"  "Reorder items on the build queue" "you can pick an item and place it somewhere else on the build queue." \
   	       "Add item"  "Queue a build item manually" "lets you choose an item from the list of all available source trees" \
   	       "Remove item"  "Remove an item from the build queue" " " \
   	       "Build"  "Builds all items found on the build queue" "make sure the order of the queue is sane before compiling." \
   	       "Install"  "Installs all available Debian packages (dangerous)" "this is usually not needed. better solve conflicts manually." \
	       "Move"  "Moves files to destination (dangerous)" "this is usually not needed. better solve conflicts manually." \
   	       "Custom"  "Invokes previously defined custom scripts"  "edit this script to define these scripts." \
   	       "Help"  "Displays help" " " \
   	       "Quit"  "Exit autoe" "the build queue can be restored by choosing 'Check trunk' again." \
   	       2> /tmp/autoe-menu1
   
   val=`cat /tmp/autoe-menu1`
   if [ "$val" = "Batch Run" ]; then
   	e_checkout
   	e_checkupdates "batch"
   	e_build
   	e_runbatchcommands
   elif [ "$val" = "Update trunk" ]; then
   	e_checkout
   elif [ "$val" = "Check trunk" ]; then
   	e_checkupdates
   elif [ "$val" = "View list" ]; then
   	e_printlist
   elif [ "$val" = "Reorder list" ]; then
   	e_reorder
   elif [ "$val" = "Add item" ]; then
   	e_add
   elif [ "$val" = "Remove item" ]; then
   	e_remove
   elif [ "$val" = "Build" ]; then
   	e_build
   elif [ "$val" = "Install" ]; then
   	e_install
   elif [ "$val" = "Move" ]; then
   	e_move
   elif [ "$val" = "Custom" ]; then
   	e_custom
   elif [ "$val" = "Help" ]; then
   	e_printhelp
   elif [ "$val" = "Quit" ]; then
	rm -f /tmp/autoe-*
   	reset
   	exit
   else
	rm -f /tmp/autoe-*
	reset
   	exit
   fi
done
rm -f /tmp/autoe-*
reset

