#---------------------------------------------------------------------
##
##=head1 SYNOPSIS
##
## Functions for dealing with the actual compiling/installation of spells
## and walking through casts 'pass 4' pipeline. If BUILD_API is '1'
##
##=head1 DESCRIPTION
##
## Contains functions for the build api version 1
## which has the following steps:
## PRE_BUILD -> BUILD -> POST_BUILD -> POST_INSTALL -> TRIGGERS
##
##=head1 COPYRIGHT
##
## Copyright (C) 2004 The Source Mage Team <http://www.sourcemage.org>
##
##=head1 FUNCTIONS
#---------------------------------------------------------------------

#---------------------------------------------------------------------
## This runs through the phase 4 pipeline of building and installing
## a spell for BUILD_API 1.
#---------------------------------------------------------------------
function run_build_spell() {
  debug "build_api/api1" "run_build_spell"
  C_LOG=$TMP_DIR/$SPELL.compile.log
  C_FIFO=/dev/stdout
  
  rm -f $C_LOG
  touch $C_LOG
  if [[ $SCREEN_NAME ]] ; then  
    screen_new_window "$SCREEN_NAME" $SCREEN_CAST_WIN "cast $SPELL" \
      tail -f -s 0.1 $C_LOG
    screen_switch_window "$SCREEN_NAME" $SCREEN_MAIN_WIN

    VOYEUR_STDOUT=/dev/null
    VOYEUR_STDERR=/dev/null
  elif [ "$VOYEUR" == "on" -a -z "$SILENT" ] ; then
    VOYEUR_STDOUT=/dev/stdout
    VOYEUR_STDERR=/dev/stderr
  else
    VOYEUR_STDOUT=/dev/null
    VOYEUR_STDERR=/dev/null
  fi
  # should OPTS get set here?

  local PROTECT_SORCERY=yes
  local rs

  # This is an experiment, If we have actual interesting return codes
  # from here, the caller can figure out what to do
  # as opposed to trying to cram it all in here
  (
    run_pre_build                         || return 1
    run_build                             || return 2
    run_post_build                        &&
    run_post_install                      || return 3
  )
  rs=$?
  
  if [[ $SCREEN_NAME ]] && [ $rs -gt 0 ] ; then
    screen_move_window "$SCREEN_NAME" $SCREEN_CAST_WIN $SCREEN_LAST_FAILED_CAST_WIN
    screen_name_window "$SCREEN_NAME" $SCREEN_LAST_FAILED_CAST_WIN "Failed $SPELL"
    screen_kill_window "$SCREEN_NAME" $SCREEN_CAST_WIN
    screen_notify "$SCREEN_NAME" "Last failed cast at $SCREEN_LAST_FAILED_CAST_WIN"
  elif [[ $SCREEN_NAME ]]  ; then
    screen_kill_window "$SCREEN_NAME" $SCREEN_CAST_WIN
  fi
  
  # Triggers don't run in the window
  [ $rs -gt 0 ] && return $rs
  run_triggers || return 4
  
  return $rs
}

#---------------------------------------------------------------------
## This phase of casting involves unpacking the source into the
## source directories. If a PRE_BUILD file exists in SCRIPT_DIRECTORY
## and is executable it is run in preference to the default_pre_build.
#---------------------------------------------------------------------
function run_pre_build() {

  debug "build_api/api1" "run_pre_build()"
  message  "${MESSAGE_COLOR}Building"  \
           "${SPELL_COLOR}${SPELL}"    \
           "${DEFAULT_COLOR}"

  rm_source_dir
  mkdir -p  $BUILD_DIRECTORY
  cd  $BUILD_DIRECTORY

  persistent_load &&
  if  [  -x  $SCRIPT_DIRECTORY/PRE_BUILD  ];  then
    debug "build_api/api1" "run_pre_build() - Prebuild script exists, now sourcing "
    . $SCRIPT_DIRECTORY/PRE_BUILD
  else
    debug "build_api/api1" "run_pre_build() - Prebuild script not found, using default"
    default_pre_build
  fi &&
  persistent_save
}


#---------------------------------------------------------------------
## Starts up the compile logs, turns on the various environment
## settings that need to be on, eventually gets around to running
## BUILD or default_build, then does other things it shouldn't do.
#---------------------------------------------------------------------
function run_build()  {

  debug "build_api/api1" "Starting run_build()"

  echo  "Compile log for $SPELL $VERSION Built on `date  -u`"  >  $C_LOG
  echo  "Using gcc version: `gcc -dumpversion`" >> $C_LOG

  # slight bug here if SOURCE_DIRECTORY doesnt exist
  [  -d  "$SOURCE_DIRECTORY"  ]  &&
  cd      $SOURCE_DIRECTORY

  invoke_build_dir
  invoke_gcc2
  optimize
  invoke_installwatch

  message -n "Installing in dir: "
  pwd
  message "$SPELL    $VERSION"

  run_config_loc
  (
    persistent_load &&
    if  [  -x  $SCRIPT_DIRECTORY/BUILD  ];  then
      .  $SCRIPT_DIRECTORY/BUILD
    else
      default_build
    fi &&
    persistent_save
  ) 2> >(tee -a $C_LOG 1>&2 >> $VOYEUR_STDERR) \
     > >(tee -a $C_LOG >> $VOYEUR_STDOUT) # see bug 7201

  if  [  "$?"  !=  0  ];  then
    message  "${PROBLEM_COLOR}"      \
             "! Problem Detected !"  \
             "${DEFAULT_COLOR}"
    return 1
  fi 
  echo  "Compile log for $SPELL $VERSION Completed Build on `date  -u`"  >>  $C_LOG

}


#---------------------------------------------------------------------
## Checks for a POST_BUILD file in SCRIPT_DIRECTORY, and if it is
## executable, runs it. This file is run after BUILD and before
## POST_INSTALL. Its purpose is to bookend BUILD and shutoff installwatch.
#---------------------------------------------------------------------
function run_post_build() {

  debug "build_api/api1" "Starting run_post_build()"
  persistent_load &&
  if  [  -x  $SCRIPT_DIRECTORY/POST_BUILD  ];  then
           . $SCRIPT_DIRECTORY/POST_BUILD
  else
    default_post_build
  fi
  persistent_save

  # Lock made in prepare_install
  unlock_resources "libgrimoire" "install"

}


#---------------------------------------------------------------------
## Checks for a POST_INSTALL file in SCRIPT_DIRECTORY, and if it is
## executable, runs it. This file is used for extra files that need
## to be installed, but not tracked by installwatch.
#---------------------------------------------------------------------
function run_post_install() {

  debug "build_api/api1" "Starting run_post_install()"
  persistent_load &&
  if    [  -x  $SCRIPT_DIRECTORY/POST_INSTALL  ]
  then
    . $SCRIPT_DIRECTORY/POST_INSTALL
  fi &&
  persistent_save
}


#---------------------------------------------------------------------
## @Type API
## Creates the source directory and unpacks the source package into it.
## Used if no PRE_BUILD script is found for a spell.
#---------------------------------------------------------------------
function real_default_pre_build() {

  debug "build_api/api1" "Starting real_default_pre_build() - SOURCE=$SOURCE SOURCE_DIRECTORY=$SOURCE_DIRECTORY"
  mk_source_dir        $SOURCE_DIRECTORY  &&
  unpack_file

}




#---------------------------------------------------------------------
## @Type API
## Used if no BUILD script is found for a spell
## Default build is:
## <pre>
##  ./configure  --build=$BUILD        \
##               --prefix=/usr         \
##               --sysconfdir=/etc     \
##               --localstatedir=/var  \
##               $OPTS                 &&
##  make                               &&
##  prepare_install                    &&
##  make    install
## </pre>
##
#---------------------------------------------------------------------
function real_default_build() {

  debug "build_api/api1" "Starting real_default_build()"
  OPTS="$OPTS --build=${BUILD}"
  #If this switches are used, they _may_ stop distcc and ccache from working
  # for some spells (bug 3798)
  #  We could write wrappers for all of the possible binaries
  [[ $CROSS_INSTALL == on ]] && OPTS="$OPTS --host=${HOST}"

  ./configure --prefix=${INSTALL_ROOT}/usr  \
          --sysconfdir=${INSTALL_ROOT}/etc  \
       --localstatedir=${INSTALL_ROOT}/var  \
              --mandir=${INSTALL_ROOT}/usr/share/man   \
             --infodir=${INSTALL_ROOT}/usr/share/info  \
                       $OPTS                 &&
  make                                       &&
  prepare_install                            &&
  make    install

}



#---------------------------------------------------------------------
## @Type API
## Installs configuration files and documentation.  Stops installwatch.
## Used if no POST_BUILD script is found for a spell.
##
#---------------------------------------------------------------------
function real_default_post_build() {

  debug "build_api/api1" "Starting real_default_post_build()"

  install_xinetd
  install_initd
  install_pam_confs
  install_desktop_files
  gather_docs
  devoke_installwatch
  init_post_install
  ldconfig
  # release_saved_libraries
  cd  /

}

#---------------------------------------------------------------------
## @License
##
## This software 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; either version 2 of the License, or
## (at your option) any later version.
##
## This software 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.
##
## You should have received a copy of the GNU General Public License
## along with this software; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
##
#---------------------------------------------------------------------
