#!/bin/bash
#---------------------------------------------------------------------
## @Synopsis Functions for dealing with the actual
## compiling/installation of spells and walking through casts 'pass 4' pipeline.
## @Copyright Copyright (C) 2002 The Source Mage Team
## &lt;http://www.sourcemage.org&gt;
## @Globals $SGL_LIBRARY_MODULES $GRIMOIRE $BUILD_API $USE_FUNCTIONS
## A spell follows the following path during its installation:
## PREPARE -&gt; DETAILS -&gt; PRE_BUILD -&gt; BUILD, or COMPILE/INSTALL -&gt;
## POST_BUILD -&gt; POST_INSTALL -&gt; TRIGGERS
## Each of these steps, along with some interim steps of dealing with
## conflicts and security are handled here as well.
#---------------------------------------------------------------------

#---------------------------------------------------------------------
## This is used to dynamically setup an api environment for a spell
## into the build api that it is specified to use. (ie split BUILD or
## no split BUILD).
#---------------------------------------------------------------------
function load_build_api() {

  debug "libcast" "Starting load_build_api"

  source $SGL_LIBRARY_MODULES/build_api/common
  case $BUILD_API in
    1) source $SGL_LIBRARY_MODULES/build_api/api1 ;;
    2) source $SGL_LIBRARY_MODULES/build_api/api2 ;;
    *) message "${PROBLEM_COLOR}Unknown build api version $BUILD_API, for" \
               "$SPELL!!${DEFAULT_COLOR}"
       message "Please update sorcery and see if the problem goes away."
       message "If it doesnt this may be a bug, please contact" \
               "the sorcery team. Thanks."
       return 1 ;;
  esac
  load_functions_file
}

#---------------------------------------------------------------------
## Load the grimoire and section level FUNCTIONS file
#---------------------------------------------------------------------
function load_functions_file() {
  # the following allows spell writers to override certain functions
  # in the build pipeline
  USE_FUNCTIONS=${USE_FUNCTIONS:-on}
  if [[ $USE_FUNCTIONS == "on" ]] ; then
    [ -x $GRIMOIRE/FUNCTIONS ] && . $GRIMOIRE/FUNCTIONS
    [ -x $SECTION_DIRECTORY/FUNCTIONS ] && . $SECTION_DIRECTORY/FUNCTIONS
  elif [[ $USE_FUNCTIONS == "grimoire" ]] ; then
    [ -x $GRIMOIRE/FUNCTIONS ] && . $GRIMOIRE/FUNCTIONS
  elif [[ $USE_FUNCTIONS == "section" ]] ; then
    [ -x $SECTION_DIRECTORY/FUNCTIONS ] && . $SECTION_DIRECTORY/FUNCTIONS
  fi
  return 0
}

#---------------------------------------------------------------------
## Load the grimoire and section level 'libcompat' file
## Spells use this for compatibility checking. It is supposed to be
## lighter-weight than FUNCTIONS.
#---------------------------------------------------------------------
function load_libcompat() {
  [ -x $GRIMOIRE/libcompat ] && . $GRIMOIRE/libcompat
  [ -x $SECTION_DIRECTORY/libcompat ] && . $SECTION_DIRECTORY/libcompat
  return 0
}

#---------------------------------------------------------------------
## Loads up this environment with the special configuration values
## that the spell needs. Typically the mode of communication between
## CONFIGURE/DEPENDS to PRE_BUILD, BUILD, COMPILE, INSTALL, etc.
## @Globals $SPELL_CONFIG $DEPENDS_CONFIG
#---------------------------------------------------------------------
function prepare_spell_config()  {

  SPELL_CONFIG=$DEPENDS_CONFIG/$SPELL
  if  !  [  -x  $SPELL_CONFIG  ];  then
    touch       $SPELL_CONFIG
    chmod  a+x  $SPELL_CONFIG
  fi

  . $SPELL_CONFIG

}

#---------------------------------------------------------------------
## Prompts the user about spells that are in conflict with the current
## spell and allows them to dispel them. If the user chooses not to
## dispel the conflicting spell, the function returns 1
## @param dis-allow conflict with anything in this list, normally used
##        to prevent self conflicts
## @return nothing if the user dispels the conflicting spell
## @return 1 if the user chooses not to dispel the conflicting spell
#---------------------------------------------------------------------
function run_conflicts() {

  debug "build_api/common" "Starting run_conflicts() on $SPELL"
  local ignore_conflict=$1
  local each

  if  [  -x  $SCRIPT_DIRECTORY/CONFLICTS  ]; then
    local CONFLICTS=$(
        persistent_load
        . $SCRIPT_DIRECTORY/CONFLICTS
        persistent_save
    )

    local tmp to_dispel=""
    for  tmp  in  $CONFLICTS  ;  do
      local spell_and_default
      explode  $tmp  ':'  spell_and_default
      local skip=no
      for each in $ignore_conflict ; do
        [[ $each == "${spell_and_default[0]}" ]] && skip=yes
      done
      [[ "$skip" == "yes" ]] && continue

      local text="${SPELL_COLOR}${SPELL}${MESSAGE_COLOR} conflicts with"
      text="$text ${SPELL_COLOR}${spell_and_default[0]}${MESSAGE_COLOR}."
      text="$text Dispel"
      text="$text ${SPELL_COLOR}${spell_and_default[0]}${MESSAGE_COLOR}?"

      if  query  "$text"  ${spell_and_default[1]}  ;  then
        to_dispel="$to_dispel ${spell_and_default[0]}"
        echo  ${spell_and_default[0]} >>  $CONFLICT_LIST
      else
        echo  $SPELL  >>  $FAILED_LIST
        return  1
      fi

      dispel  $to_dispel
    done
  fi

}


#---------------------------------------------------------------------
## Asks the user about init and xinetd services
##
## expcetd $SCRIPT_DIRECTORY to be setable, any file one level deep in
## $SCRIPT_DIRECTORY/xinetd.d or $SCRIPT_DIRECTORY/init.d is assumed to be
## a service
## 
## the following persistent variables may be set:
## XINETD_ENABLED XINETD_DISABLED
## INIT_ENABLED INIT_DISABLED
## XINETD_INSTALLED XINETD_NOT_INSTALLED
## INIT_INSTALLED INIT_NOT_INSTALLED
##
## They are all lists used by the list_add/list_find functions. The union
## of FOO_ENABLED and FOO_DISABLED should be exactly equivalent to
## FOO_INSTALLED. FOO_ENABLED and FOO_DISABLED have an empty intersection set.
#---------------------------------------------------------------------
function query_services() {
  local XINETD_SCRIPTS
  local INIT_SCRIPTS
  local btmp xtmp itmp 
  local tmp retvar
  local XINETD INIT BOTH found
  local new_init_provides

  test -d $SCRIPT_DIRECTORY/xinetd.d &&
  XINETD_SCRIPTS=$(find $SCRIPT_DIRECTORY/xinetd.d -maxdepth 1 -type f \
                                                         -a -not -name '.*')

  test -d $SCRIPT_DIRECTORY/init.d &&
  INIT_SCRIPTS=$(find $SCRIPT_DIRECTORY/init.d -maxdepth 1 -type f \
                                  -a -not -name '.*' -a -not -name '*.conf')

  local new_init_inst new_init_ninst new_init_enab new_init_disab
  local new_xinetd_inst new_xinetd_ninst new_xinetd_enab new_xinetd_disab

  for xtmp in $XINETD_SCRIPTS; do
    for itmp in $INIT_SCRIPTS; do
      if [[ $(basename $xtmp) == $(basename $itmp) ]] ; then
        list_add BOTH $(basename $itmp)
        found=1
        break
      fi
    done
  done

  for tmp in $INIT_SCRIPTS; do
    tmp=$(basename $tmp)
    list_find $tmp $BOTH || list_add INIT $tmp
    # if the script is ESSENTIAL or RECOMMENDED default to yes unless
    # the user previously said no
    if grep -Fq 'ESSENTIAL=yes' $SCRIPT_DIRECTORY/init.d/$tmp ||
       grep -Fq 'RECOMMENDED=yes' $SCRIPT_DIRECTORY/init.d/$tmp &&
       ! list_find $tmp $INIT_NOT_INSTALLED; then
       list_add INIT_INSTALLED $tmp
       list_add INIT_ENABLED $tmp
       list_remove INIT_DISABLED $tmp
     fi
  done

  for tmp in $XINETD_SCRIPTS; do
    tmp=$(basename $tmp)
    list_find $tmp $BOTH || list_add XINETD $tmp
  done

  local d1 d2
  for tmp in $BOTH ; do
    message "${QUERY_COLOR}Would you like to install the init and/or" \
            "xinetd script for $tmp?${DEFAULT_COLOR}"

    if [[ $DEF_INIT_VS_XINETD == on ]]; then
      d1=$DEF_INSTALL_INIT; d2=n
    else
      d1=n; d2=$DEF_INSTALL_XINETD
    fi
    dual_service_query $tmp choice "$XINETD_INSTALLED" "$XINETD_NOT_INSTALLED" \
                                   "$INIT_INSTALLED" "$INIT_NOT_INSTALLED" \
                                   "$d1" "$d2"
    if [[ $choice == both ]] ; then
      list_add new_init_inst $tmp
      list_add new_xinetd_inst $tmp
      message "${QUERY_COLOR}Would you like to enable $tmp through init" \
              "and/or xinetd?${DEFAULT_COLOR}"

      if [[ $DEF_INIT_VS_XINETD ]]; then
        d1=$DEF_ENABLE_INIT; d2=n
      else
        d1=n;d2=$DEF_ENABLE_XINETD
      fi
      dual_service_query $tmp choice "$XINETD_ENABLED" "$XINETD_DISABLED" \
                                     "$INIT_ENABLED" "$INIT_DISABLED" \
                                     "$d1" "$d2"

      case $choice in
          both) list_add new_init_enab $tmp
                list_add new_xinetd_enab $tmp
                ;;
          init) list_add new_init_enab $tmp
                list_add new_xinetd_disab $tmp
                ;;
        xinetd) list_add new_init_disab $tmp
                list_add new_xinetd_enab $tmp
                ;;
       neither) list_add new_init_disab $tmp
                list_add new_xinetd_disab $tmp
                ;;
      esac
    elif [[ $choice == init ]] ; then
      list_add new_init_inst $tmp
      list_add new_xinetd_ninst $tmp
      if service_query $tmp "Enable init script $tmp?" "$INIT_ENABLED" \
                            "$INIT_DISABLED" "$DEF_ENABLE_INIT" \
                             new_init_enab new_init_disab; then
        init_prepare_install "$tmp" "$INIT_PROVIDES" new_init_provides
      fi
    elif [[ $choice == xinetd ]] ; then
      list_add new_init_ninst $tmp
      list_add new_xinetd_inst $tmp
      service_query $tmp "Enable xinetd script $tmp?" "$XINETD_ENABLED" \
                         "$XINETD_DISABLED" "$DEF_ENABLE_XINETD" \
                         new_xinetd_enab new_xinetd_disab
    else
      list_add new_init_ninst $tmp
      list_add new_xinetd_ninst $tmp
    fi
  done

  for tmp in $INIT; do
    if grep -Fq 'ESSENTIAL=yes' $SCRIPT_DIRECTORY/init.d/$tmp ; then
      message "Init script $tmp is \"ESSENTIAL\" for system startup," \
              "\nit is recommended that you answer yes to the following" \
              "\nqueries unless you know exactly what you're doing."
    elif grep -Fq 'RECOMMENDED=yes' $SCRIPT_DIRECTORY/init.d/$tmp ; then
      message "Init script $tmp is \"RECOMMENDED\" for system startup," \
            "\nit is recommended that you answer yes to the following queries."
    fi
    if service_query $tmp "Install init script $tmp?" "$INIT_INSTALLED" \
                          "$INIT_NOT_INSTALLED" "$DEF_INSTALL_INIT" \
                          new_init_inst new_init_ninst; then
      if service_query $tmp "Enable init script $tmp?" "$INIT_ENABLED" \
                            "$INIT_DISABLED" "$DEF_ENABLE_INIT" \
                            new_init_enab new_init_disab; then
        init_prepare_install "$tmp" "$INIT_PROVIDES" new_init_provides
      fi
    fi
  done
  for tmp in $XINETD; do
    if service_query $tmp "Install xinetd script $tmp?" "$XINETD_INSTALLED" \
                          "$XINETD_NOT_INSTALLED" "$DEF_INSTALL_XINETD" \
                          new_xinetd_inst new_xinetd_ninst; then
      service_query $tmp "Enable xinetd script $tmp?" "$XINETD_ENABLED" \
                         "$XINETD_DISABLED" "$DEF_ENABLE_XINETD" \
                         new_xinetd_enab new_xinetd_disab
    fi
  done

  # removing all of these is necessary incase some init/xinetd scripts were
  # originally in the spell but were later removed, besides its harmless
  persistent_remove INIT_INSTALLED
  persistent_remove INIT_NOT_INSTALLED
  persistent_remove INIT_ENABLED
  persistent_remove INIT_DISABLED
  persistent_remove XINETD_INSTALLED
  persistent_remove XINETD_NOT_INSTALLED
  persistent_remove XINETD_ENABLED
  persistent_remove XINETD_DISABLED

  persistent_remove INIT_PROVIDES

  if [[ $INIT ]] || [[ $BOTH ]] ; then
    service_store INIT_INSTALLED "$new_init_inst"
    service_store INIT_NOT_INSTALLED "$new_init_ninst"
    service_store INIT_ENABLED "$new_init_enab"
    service_store INIT_DISABLED "$new_init_disab"
  fi

  if [[ $XINETD ]] || [[ $BOTH ]] ; then
    service_store XINETD_INSTALLED "$new_xinetd_inst"
    service_store XINETD_NOT_INSTALLED "$new_xinetd_ninst"
    service_store XINETD_ENABLED "$new_xinetd_enab"
    service_store XINETD_DISABLED "$new_xinetd_disab"
  fi

  if [[ $new_init_provides ]] ; then
    service_store INIT_PROVIDES "$new_init_provides"
  fi

  if [[ $XINETD_INSTALLED ]] ; then
    optional_depends xinetd "" "" "for $XINETD_INSTALLED"
  fi
}


#---------------------------------------------------------------------
## Determines what the best default answer should be then gives the
## user a menu of neither, init, xinetd, or both to choose from.
## This is for the case of a service being provided by either init or xinetd
##
## @param service name
## @param return variable to put answer in
## @param list to look in for a default of yes to xinetd
## @param list to look in for a default of no to xinetd
## @param list to look in for a default of yes to init
## @param list to look in for a default of no to init
## @param default for xinetd if not found in either of the xinetd lists
## @param default for init if not found in either of the init lists
##
## @return nothing of importance, returns through a pointer
## @stdout a menu sans question, the caller needs to present the question
#---------------------------------------------------------------------
function dual_service_query() {
  local service=$1
  local returnvar=$2
  local XY=$3
  local XN=$4
  local IY=$5
  local IN=$6
  local xinetd_default=$7
  local init_default=$8

  [[ $xinetd_default == off ]] && xinetd_default=n
  [[ $xinetd_default == on ]] && xinetd_default=y
  [[ $init_default == off ]] && init_default=n
  [[ $init_default == on ]] && init_default=y

  if list_find $service $XY ; then
    xinetd_default=y
  elif list_find $service $XN ; then
    xinetd_default=n
  fi

  if list_find $service $IY ; then
    init_default=y
  elif list_find $service $IN ; then
    init_default=n
  fi
  
  if [[ $init_default == y ]] && [[ $xinetd_default == y ]] ; then
    default=3
  elif [[ $xinetd_default == y ]] ; then
    default=2
  elif [[ $init_default == y ]] ; then
    default=1
  else
    default=0
  fi
  select_list $returnvar $default neither init xinetd both
}


#---------------------------------------------------------------------
## Determines what the best default answer should be then asks the
## user given question and adds the service to one of two lists
## @param service name
## @param question to ask
## @param list to look in for a default of yes
## @param list to look in for a default of no
## @param default if not found in either of the above two lists
## @param store in this list if the answer is yes
## @param store in this list if the answer is no
## @return true if yes false if no
## @stdout a query supplied by the caller
#---------------------------------------------------------------------
function service_query() {
  local service=$1
  local question=$2
  local L1=$3
  local L2=$4
  local real_default=$5
  local yes_list=$6
  local no_list=$7

  local default
  if list_find $service $L1 ; then
    default=y
  elif list_find $service $L2 ; then
    default=n
  else
    [[ $real_default == off ]] && real_default=n
    [[ $real_default == on ]] && real_default=y
    default=$real_default
  fi

  if query "$question" $default ; then
    list_add $yes_list $service
    true
  else
    list_add $no_list $service
    false
  fi
}

#---------------------------------------------------------------------
## Internal wrapper around the task of adding a persistent variable
## then storing something in it, or unsetting whatever used to be in it
#---------------------------------------------------------------------
function service_store() {
  local VARNAME=$1
  local list=$2
  persistent_add $VARNAME
  if [[ $list ]] ; then
    eval $VARNAME=\"$list\"
  else
    unset $VARNAME
  fi
}


#---------------------------------------------------------------------
## Installs the scripts selected from query_services
#---------------------------------------------------------------------
function install_xinetd() {
  if  [[  $XINETD_INSTALLED  ]] ; then
    local install_dir=$INSTALL_ROOT/etc/xinetd.d
    mkdir  -p  $install_dir
    pushd "$SCRIPT_DIRECTORY/xinetd.d" >/dev/null

    # install and enable
    for  FILE in  $XINETD_INSTALLED; do
      if ! test -e $FILE ; then
        message "${PROBLEM_COLOR}Xinetd script $FILE doesnt exist," \
                "but was selected, this may be a sorcery bug${DEFAULT_COLOR}"
        continue
      fi
      if list_find $FILE $XINETD_ENABLED; then
        message "Installing and enabling xinetd script $FILE to $install_dir"
        install_xinetd_sub $FILE no $install_dir
      elif list_find $FILE $XINETD_DISABLED; then
        message "Installing and disabling xinetd script $FILE to $install_dir"
        install_xinetd_sub $FILE yes $install_dir
      else
        message "${PROBLEM_COLOR}Xinetd script $FILE is in installed list" \
                "but wasnt enabled or disabled, this may be a sorcery bug" \
                "${DEFAULT_COLOR}"
      fi
    done
    popd >/dev/null
  fi
}

#---------------------------------------------------------------------
## Does the dirty work involved in installing an xinetd script
## this includes setting the disabled field appropriately and
## not trampling on pre-existing files by default
#---------------------------------------------------------------------
function install_xinetd_sub() {
  local file=$1
  local bfile=$(basename $1)
  local state=$2
  local install_dir=$3
  local tmp_file=$TMP_DIR/$bfile
  local inst_file=$install_dir/$bfile
  cp  $file $tmp_file

  set_xinetd_state $tmp_file $state

  if test -e $inst_file &&
     ! grep -v disable $inst_file|diff - $file &>/dev/null ; then
    message "${QUERY_COLOR}$inst_file differs from the default $file," \
            "what would you like to do?${DEFAULT_COLOR}"
    select_list choice 0 "ignore" "overwrite" "overwrite/backup"
    case $choice in
      "overwrite/backup")
        local backup=$inst_file.$(date +'%Y%m%d%H%M')
        mv $inst_file $backup
        # disable the backup
        set_xinetd_state $backup yes
        cp $tmp_file $inst_file ;;
      overwrite) cp $tmp_file $inst_file ;;
    esac
  else
    cp $tmp_file $inst_file
  fi
}

#---------------------------------------------------------------------
## Handles the logic of enabling or disabling of an xinetd script
#---------------------------------------------------------------------
function set_xinetd_state() {
  local file=$1
  local state=$2
  if grep -q "\s*disable" $file ; then
    sedit "s/disable\s*=.*/disable = $state/" $file
  else
    sedit "s/}/disable = $state\n}/" $file
  fi
}


#---------------------------------------------------------------------
## Copies any init.d files from the SCRIPT_DIRECTORY to the /etc/init.d.
## Hopefully saving the old one if it exists and only setting the
## executable bit if the user specified that the init.d script should be
## started at bootup.
#---------------------------------------------------------------------
function install_initd() {
  if  [[  $INIT_INSTALLED  ]] ; then
    local install_dir=$INSTALL_ROOT/etc/init.d
    mkdir  -p  $install_dir
    pushd "$SCRIPT_DIRECTORY/init.d" >/dev/null

    # install and enable
    for  FILE in  $INIT_INSTALLED; do
      message "${QUERY_COLOR}installing $FILE${DEFAULT_COLOR}"
      if ! test -e $FILE ; then
        message "${PROBLEM_COLOR}Init script $FILE doesnt exist," \
                "but was selected, this may be a sorcery bug${DEFAULT_COLOR}"
        continue
      fi
      if list_find $FILE $INIT_ENABLED; then
        init_install enabled $FILE
      elif list_find $FILE $INIT_DISABLED; then
        init_install disabled $FILE
      else
        message "${PROBLEM_COLOR}Init script $FILE is in installed list" \
                "but wasnt enabled or disabled, this may be a sorcery bug" \
                "${DEFAULT_COLOR}"
      fi
    done
    popd >/dev/null
  fi
}


#---------------------------------------------------------------------
## Gets the cast lock for us and ensures that we've waited for all
## solo/non-solo casts to complete
#---------------------------------------------------------------------
function acquire_cast_lock() {
  # locking - blocks normal spells if a solo cast is running,
  # solo casts if any cast is running
  message "${MESSAGE_COLOR}Waiting for any${DEFAULT_COLOR} ${FILE_COLOR}" \
          "Solo${DEFAULT_COLOR} ${MESSAGE_COLOR}casts to complete..." \
          "${DEFAULT_COLOR}"
  lock_resources "solo" "cast"
  if test -f $SOLO && grep -q "^$SPELL$" $SOLO || 
     [ -f $SCRIPT_DIRECTORY/SOLO ]
  then #SOLO spell
    message -n "${MESSAGE_COLOR}Waiting for${DEFAULT_COLOR} ${SPELL_COLOR}" \
               "all other${DEFAULT_COLOR} ${MESSAGE_COLOR}spells to" \
               " complete...${DEFAULT_COLOR}"
    excllock_resources "cast" "$SPELL"
  else
    message -n "${MESSAGE_COLOR}Waiting for any other casts of" \
               "${DEFAULT_COLOR} ${SPELL_COLOR}$SPELL${DEFAULT_COLOR}" \
               " ${MESSAGE_COLOR}to complete...${DEFAULT_COLOR}"
    lock_resources "cast" "$SPELL"
    unlock_resources "solo" "cast"
  fi
  message " done."
}

#---------------------------------------------------------------------
## Takes the compile log and stuffs it into
## our compile log directory.
#---------------------------------------------------------------------
function create_compile_log()  {

  message  "${MESSAGE_COLOR}Creating compile log"                  \
           "${FILE_COLOR}$COMPILE_LOGS/$SPELL-$VERSION$EXTENSION"  \
           "${DEFAULT_COLOR}"
  if [[ "$STORE_CONF_LOG" == on ]] && test -e $SOURCE_DIRECTORY/config.log; then
    echo "---config.log---" >> $C_LOG
    cat $SOURCE_DIRECTORY/config.log >> $C_LOG
  fi
  if [  -z  "$EXTENSION"  ];  then
    cp  $C_LOG  $COMPILE_LOGS/$SPELL-$VERSION
  else
    $COMPRESSBIN  -f  <  $C_LOG  >  $COMPILE_LOGS/$SPELL-$VERSION$EXTENSION
  fi
}


#---------------------------------------------------------------------
## Prompts the user to view the compile log
## and deletes the temporary files too
#---------------------------------------------------------------------
function view_compile_log()  {

    debug "libcast" "In view_compile_log, C_LOG=$C_LOG"
    report $C_LOG  "Compile log"
}

#---------------------------------------------------------------------
## Report that something got installed, and possibly display the report
## Pawns the work off to <@function var.lib.sorcery.modules.libsorcery,report>
## @Globals INST_LOG
#---------------------------------------------------------------------
function report_install()  {

  debug "libcast" "In report_install, INST_LOG=$INST_LOG"
  report  $INST_LOG  "Install log"

}

#---------------------------------------------------------------------
## LC means "line count" why not just type line_count?
## @TODO This function is dumb. It should be fixed.
## @param download log file name
#---------------------------------------------------------------------
function show_download_progress()  {
  [[ $SCREEN_NAME ]] && return
  local download_log=$1
  if  [  -e  "$download_log"   ]   &&
      [  -z  "$SILENT"  ];  then

    LC_OLD=${LC_OLD:-0}

    LC=`cat  $download_log  2>/dev/null  |  wc  -l  |  tr  -d ' '`

    if  [  "$LC"  !=  "$LC_OLD"  ];  then
      let LC_OLD++
      sed  -n ${LC_OLD},${LC}p  $download_log
      LC_OLD=$LC
    fi

  fi

}

#---------------------------------------------------------------------
## Shows download progress. Waits for the download to start, and shows
## the progress until the download is done.
## Pawn most of the display out to <@function show_download_progress>
## @TODO fix the old style ad-hoc IPC
## @param Spell to show the download progress for
#---------------------------------------------------------------------
function show_downloading()  {

  local SPELL=$1
  local download_log=$(get_spell_dl_log $SPELL)
  debug "cast" "Started show_downloading() on $SPELL from $download_log"

  # poke around waiting for downloading to start
  while ! ( [[ $download_log ]] && 
            [  -e "$download_log"  ] ) 
  do
    sleep 1
  done

  # isn't this out of band ipc great?
  until [  -f "${download_log}.done"  ] ;  do
    show_download_progress $download_log
    sleep 1
  done
  
  show_download_progress $download_log
  debug "libcast" "Out of show_downloading"
}

#---------------------------------------------------------------------
## Gets the filename of the download log file
## @param Spell 
## @Stdout file name
#---------------------------------------------------------------------
function get_spell_dl_log() {
  echo "$TMP_DIR/download.$1"
}

#---------------------------------------------------------------------
## @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
##
#---------------------------------------------------------------------
