#---------------------------------------------------------------------
##
##=head1 SYNOPSIS
##
## Functions for dealing with the actual compiling/installation of spells
## and walking through casts 'pass 4' pipeline.
##
##=head1 DESCRIPTION
##
## A spell follows the following path during its installation:
## PREPARE -> DETAILS -> PRE_BUILD -> BUILD, or COMPILE/INSTALL ->
## POST_BUILD -> POST_INSTALL -> TRIGGERS
## Each of these steps, along with some interim steps of dealing with
## conflicts and security are handled here as weell.
##
##=head1 COPYRIGHT
##
## Copyright (C) 2002 The Source Mage Team <http://www.sourcemage.org>
##
##=head1 FUNCTIONS
#---------------------------------------------------------------------

#---------------------------------------------------------------------
## 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 ;;
    *) source $SGL_LIBRARY_MODULES/build_api/api1 ;;
  esac

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


#---------------------------------------------------------------------
## 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.
#---------------------------------------------------------------------
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 if they want to invoke the services in
## SCRIPT_DIRECTORY/xinetd.d/* via xinetd.
## An optional depends is set on or off depending on whether or not
## the user wants to invoke a spell via xinetd
#---------------------------------------------------------------------
function use_xinetd()  { (

  debug "cast" "In use_xinetd()"
  
  if  [  -d  $SCRIPT_DIRECTORY/xinetd.d  ]  &&
      !  grep  -q  "SERVICES="  $SPELL_CONFIG
  then

    debug "cast" "use_xinetd: found an xinetd directory - processing"
    ALL_SERVICES=`cat  $SCRIPT_DIRECTORY/xinetd.d/*  |
                  grep  "service"                    |
                  sed   "s/service //"`
                  
    debug "cast" "use_xinetd: ALL_SERVICES: '$ALL_SERVICES'"

    # only looking for services to install, non-selected services
    # will be installed and disabled in install_xinetd_confs().
    for  SERVICE  in  $ALL_SERVICES;  do
      if    query  "Invoke $SERVICE via xinetd?"  y
      then 
        SERVICES="$SERVICE $SERVICES"
      else
        SERVICES_DISABLE="$SERVICE_DISABLE $SERVICES_DISABLE" 
      fi
    done

    debug "cast" "use_xinetd: to install SERVICES: '$SERVICES'"
    debug "cast" "use_xinetd: to disable SERVICES_DISABLE: '$SERVICES_DISABLE'"
    debug "cast" "setting up depends for services"

    for  SERVICE  in  $SERVICES;  do
      for  FILE  in  `ls  $SCRIPT_DIRECTORY/xinetd.d/*`;  do

         if  grep  -q   "service $SERVICE"  $FILE   &&
             grep  -q   "stunnel"           $FILE;  then
           add_depends  "$SPELL"  "stunnel"  "on"  "optional"
         fi

      done
    done

    if    [  -n  "$SERVICES"  ]
    then  add_depends  "$SPELL"  "xinetd"  "on"   "optional"
    else  add_depends  "$SPELL"  "xinetd"  "off"  "optional"
    fi

    echo  "SERVICES=\"$SERVICES\""  >>  $SPELL_CONFIG
		echo  "SERVICES_DISABLE=\"$SERVICES_DISABLE\""  >> $SPELL_CONFIG

  fi

) }

#---------------------------------------------------------------------
## Installs the services selected from use_xinetd
#---------------------------------------------------------------------
function install_xinetd() { (

  if  [  -d  $SCRIPT_DIRECTORY/xinetd.d  ] 
  then
		
    SERVICES=""          # services to be installed.
		SERVICES_DISABLE=""  # services not to install.
    . $SPELL_CONFIG
    debug "cast" "use_xinetd: about to call install_xinetd_confs"

		if  [  -n  "$SERVICES"  ] ; then
  		# now we install the selected services.
			install_xinetd_confs $SERVICES
		fi
	fi
) }

#---------------------------------------------------------------------
## Prompts the user if they want the init.d scripts the current spell
## has to be installed.
#---------------------------------------------------------------------
# Automagic initscript installation.
function use_initd()  { (

  debug "cast" "In use_initd()"

  INITDSCRIPTS=""
  INITDSCRIPTS_DISABLED=""

  if  [  -d  $SCRIPT_DIRECTORY/init.d  ]  ; then
    debug "cast" "use_initd: found an init.d directory - processing"

    . $SPELL_CONFIG

    local ALL_INITSCRIPTS=`ls  $SCRIPT_DIRECTORY/init.d/ | grep  -v  '\.conf$'`
    debug "cast" "use_initd: ALL_INITSCRIPTS: '$ALL_INITSCRIPTS'"

    for  INITSCRIPT  in  $ALL_INITSCRIPTS  ;  do
      echo  "$INITDSCRIPTS $INITDSCRIPTS_DISABLED"  |  \
          grep  -Eq  "( |^)$INITSCRIPT( |$)"  &&  continue

      if  query  "Invoke $INITSCRIPT at boot via init?"  y  ;  then
        INITDSCRIPTS="$INITSCRIPT $INITDSCRIPTS"
        init_prepare_install  $INITSCRIPT
      else
        INITDSCRIPTS_DISABLED="$INITSCRIPT $INITDSCRIPTS_DISABLED"
      fi
    done
  fi
    
  tmp=$(  grep  -v  -e '^INITDSCRIPTS='  -e '^INITDSCRIPTS_DISABLED='  \
      $SPELL_CONFIG )
  echo "$tmp" > $SPELL_CONFIG
  echo  "INITDSCRIPTS=\"$INITDSCRIPTS\""  >>  $SPELL_CONFIG
  echo  "INITDSCRIPTS_DISABLED=\"$INITDSCRIPTS_DISABLED\"" >> $SPELL_CONFIG
) }

#---------------------------------------------------------------------
## 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() { (
    debug "cast" "use_initd: to install INITDSCRIPTS: '$INITDSCRIPTS'"
    debug "cast" "use_initd: to disable INITDSCRIPTS_DISABLED: '$INITDSCRIPTS_DISABLED'"
    debug "cast" "saving initscripts"
    
    INITDSCRIPTS=""
    INITDSCRIPTS_DISABLED=""
    . $SPELL_CONFIG

#    local ALL_INITSCRIPTS=`ls  $SCRIPT_DIRECTORY/init.d/ | grep  -v  '\.conf$'`
    # now we install the selected scripts.
    if  [  -n  "$INITDSCRIPTS"  ] ; then
      debug "cast" "use_initd: about to call install_initd_confs"
      install_initd_confs enabled $INITDSCRIPTS
    fi

    # and disable the others.
    if  [  -n  "$INITDSCRIPTS_DISABLED"  ] ; then
      debug "cast" "use_initd: about to disable : '$INITDSCRIPTS_DISABLED'"
      install_initd_confs disabled $INITDSCRIPTS_DISABLED
    fi
    
) }


#---------------------------------------------------------------------
## Takes the compile log, created by activate_voyeur 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 [  -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"
}


#---------------------------------------------------------------------
## Turns on logging of the output from BUILD/COMPILE/INSTALL
## Needs to be run after each script finishes because tee stops writing
## upon EOF.
#---------------------------------------------------------------------
function activate_voyeur()  {

  if  [  -z  "$SILENT"  ];  then
    case  $VOYEUR  in
      on)  tee  -a  $C_LOG  <  $C_FIFO              &  ;;
       *)  tee  -a  $C_LOG  <  $C_FIFO  >/dev/null  &  ;;
    esac
  else     tee  -a  $C_LOG  <  $C_FIFO  >/dev/null  &
  fi

}

#---------------------------------------------------------------------
## @param spellname
## calls run_details and returns the returnvalue of
## [ -f $INSTALL_CACHE/$SPELL-$VERSION-$BUILD.tar.bz2 ]
#---------------------------------------------------------------------
function can_resurect()  {
	debug "libcast" "can_resurect - $*"
	run_details		&&
	[ -f $INSTALL_CACHE/$SPELL-$VERSION-$BUILD.tar$EXTENSION ] &&
	debug "cast" "I am able to resurect."
}

function resurrect()  {  (  

  debug "libcast" "resurrect - $*"

  run_prepare   &&
  can_resurect
#  run_details  run by can_resurect now

  # needed because of build splitification
  load_build_api

  STATUS=installed

  if  spell_held  $SPELL;  then
    VERSION=`installed_version  $SPELL`
     STATUS=held
    dispel --notriggers $SPELL
  fi

  CACHE_COMP="$INSTALL_CACHE/$SPELL-$VERSION-$BUILD.tar$EXTENSION"
  CONTINUE=false

  if    [  !              -f  $CACHE_COMP   ];  then
    false
  elif  [                 -z  "$EXTENSION"  ];  then
    if  $COMPRESSBIN  -tf  $CACHE_COMP  1>/dev/null
    then
      CONTINUE=true;
    fi
  elif  $COMPRESSBIN  -tf  $CACHE_COMP
  then
    CONTINUE=true;
  fi

  if  $CONTINUE
  then
    run_conflicts    &&
    satisfy_depends  &&
		
    if  [  -n  "$EXTENSION"  ];  then
      $COMPRESSBIN   -cd   $CACHE_COMP  |  tar  -Pkx  1>/dev/null  2>&1
    else
      tar  -Pkxf  $CACHE_COMP  1>/dev/null  2>&1
    fi 

    # minor hack until I re-write this (afk 4/12/2004)
    if [ $BUILD_API == 2 ] ; then
      run_final
    else
      run_post_install 
    fi
    run_triggers
    
    add_spell     "$SPELL"  "$STATUS"  "$VERSION"
    pop_install_queue "$SPELL"
    activity_log  "cast"  "$SPELL"  "$VERSION"  "success"
    set_successful_cast  "$SPELL"
    clear_line
    message  "${RESURRECT_COLOR}Resurrected spell:"  \
             "${SPELL_COLOR}${SPELL}"                \
             "${DEFAULT_COLOR}"                      \
             "version"                               \
             "${VERSION_COLOR}${VERSION}"            \
             "${DEFAULT_COLOR}"
    cast  --fix  $SILENT  $SPELL && echo $SPELL >> $SUCCESS_LIST
  else
    echo $SPELL >> $FAILED_LIST
    false
  fi

  # run ldconfig 
	message "${MESSAGE_COLOR}Updating the shared libraries ...${DEFAULT_COLOR}"
  release_saved_libraries

)  }


#---------------------------------------------------------------------
#---------------------------------------------------------------------
function show_download_progress()  {

  if  [  -f  "$D_LOG"   ]   &&
      [  -z  "$SILENT"  ];  then

    LC_OLD=${LC_OLD:-0}

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

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

  fi

}


#---------------------------------------------------------------------
#---------------------------------------------------------------------
function show_downloading()  {

#  COMPILE="y"
  debug "cast" "Started show_downloading() on $SPELL"
  while ! ( [[ $D_LOG ]] && 
            [  -f "$D_LOG"  ] ) 
  do
    sleep 1
  done

  #The file is created in run_summon
  until [  -f "${D_LOG}.done.$SPELL"  ] ;  do
    show_download_progress
    sleep 1
  done
  
  rm "${D_LOG}.done.$SPELL"
  show_download_progress

}


#---------------------------------------------------------------------
#---------------------------------------------------------------------
function report_install()  {

  local INST_LOG=$INSTALL_LOGS/$SPELL-$VERSION
  debug "libcast" "In report_install, INST_LOG=$INST_LOG"
  report  $INST_LOG  "Install log"

}




