#!/bin/bash
#---------------------------------------------------------------------
##
##=head1 SYNOPSIS
##
## summon is a script for downloading spell source files
##
##=head1 DESCRIPTION
##
## ...
##
##=head1 COPYRIGHT
##
## Original version Copyright 2001 by Kyle Sallee
## Some parts copyright 2002 by Anders Bruun Olsen et al
## Other additions/corrections Copyright 2002 by the Source Mage Team
##
##=head1 FUNCTIONS
##
##=over 4
##
#---------------------------------------------------------------------


help() {

  cat  <<  EOF

Summon downloads single or multiple spell source files.

Example:        summon  nano hdparm sudo
Usage:          summon  [parameters] [spells]

Optional Parameters:

--from		<directory>	Specify an alternate for $SOURCE_CACHE
       					

--url		<URL>		Specify an alternate download URL

-d | --download			Force download of source, regardless of
                                 of whether it exists locally or not.

-g | --grimoire <grimoire>	Searches only the given grimoire when
                                 searching for spells to summon.
				 <grimoire> can be absolute or relative to
				 $CODEX_ROOT
				 Note that spells or the --all parameter
				 still needs to be specified.

-p | --print	<type>		Instead of downloading, print out
                                 information in some form according
                                 to the value of <type> for each spell:
                                  source   - print out the filenames
                                  one_url  - print the first url
                                  all_urls - print out all the urls
                                  raw      - print out all the file
                                  and urls, this format is meant to
                                  be re-read by summon in raw mode.

-r | --raw                      Read in urls in "raw" form, eg:
                                 file1 url1-1 url1-2 ...
                                 file2 url2-1 url2-2 ...
                                 ...

--queue				Download all spells in the install queue.
--all				Download all spells in the grimoires.
				(note: this is several gigabytes)
EOF

  exit  1

}


process_parameters()  {

if [ ! -n "$1" ]; then
  help;
fi

  while  [  -n  "$1"  ];  do

    if echo "" $1 | grep  -q "^ -"; then

      case $1 in
         --from) SOURCE_CACHE=$2;         shift 2 ;;
         --help) help;                    exit  1 ;;
          --url) BASE_URL="$2" ;          shift 2 ;;
  -d|--download) FORCE_DOWNLOAD=on;        shift 1 ;;
  -g|--grimoire) codex_set_grimoires $2;  shift 2 ;;
     -p|--print) set_print_type $2;       shift 2 ;;
        --queue) QUEUE=1;                 shift 1 ;;
          --all) SUMMON_ALL=1;            shift 1 ;; 
       -r|--raw) RAW=1;                   shift 1 ;; 
              *) help;                            ;;
      esac

    else  shift 1
    fi

  done

}


strip_parameters()  {

  while  [  -n  "$1"  ];  do

    if  echo  "" $1  |  grep  -q  "^ -";  then

      case  $1  in
        --from)  shift 2  ;;
        --help)  shift 1  ;;
         --url)  shift 2  ;;
 -d|--download)  shift 1  ;;
 -g|--grimoire)  shift 2  ;;
    -p|--print)  shift 2  ;;
       --queue)  shift 1  ;;
         --all)  shift 1  ;;
         --raw)  shift 1  ;;
             *)  shift 1  ;;
      esac

    else  echo  $1
          shift 1
    fi

  done

}

#---------------------------------------------------------------------
## @param A list of spells
## @global PRINT_TYPE
## This is mainly for summon, but might be useful for gaze as its
## an information query function.
#---------------------------------------------------------------------
function summon_print_spells() {
  local SPELLS="$*"
  [ -z "$SPELLS" ] && return 1

  for  SPELL  in  $SPELLS;  do
    # run in a subshell rather than try to unset_details
    # its a fork either way, and this way leaves us less open for surprises
    ( run_details  &&
      get_spell_files_and_urls|while read -a dl_array; do
        if [ "$PRINT_TYPE" == source ]; then
          echo "${dl_array[0]}"
        elif [ "$PRINT_TYPE" == one_url ]; then
          [ -n "${dl_array[1]}" ] && echo "${dl_array[1]}"
        elif [ "$PRINT_TYPE" == all_urls ]; then
          unset dl_array[0]
          [ -n "${dl_array[*]}" ] && echo "${dl_array[*]}"
        elif [ "$PRINT_TYPE" == raw ]; then
          echo "${dl_array[*]}"
        else
          echo "unknown value of PRINT_TYPE $PRINT_TYPE we shouldn't get here"
          echo "please file a bug if you see this, thanks."
          exit 1
        fi
      done
    )
  done
}

#---------------------------------------------------------------------
## @param A list of spells
## Will call summon_spell for each spell found in "$*"
##
#---------------------------------------------------------------------
function summon_spells() {
  local SPELLS="$*"
  local SPELL
  [ -z "$SPELLS" ] && return 1
  for  SPELL  in  $SPELLS;  do
    summon_spell $SPELL
  done
}


set_print_type() {
  PRINT_TYPE="$1"
  [ "$PRINT_TYPE" == source ]    ||
  [ "$PRINT_TYPE" == one_url ]   ||
  [ "$PRINT_TYPE" == all_urls ]  ||
  [ "$PRINT_TYPE" == raw ]       ||
  help
}

main() {

  local spells_to_get
  cd  /tmp
  process_parameters $*

  if [ -n "$RAW" ] ; then
    local line rc
    while read line; do
      # eval is needed to preserve quoting
      eval set -a $line
      download_src_args "$@" || rc=$?
    done
    return $rc
  fi

  if  [  -n  "$SUMMON_ALL"  ];  then
    spells_to_get=`codex_get_all_spells|get_basenames`
  elif [  -n  "$QUEUE"  ]; then

    # Since sometimes we'll be running in raw output mode and possibly
    # redirecting that output somewhere, we dont want to be prompting
    # the "user" about the install queue, but if stdout is a character
    # device (such as a terminal) we may as well try. Im not expecting
    # the user to redirect to a character device too often...but that
    # may be an issue at some point.
    if test -c /dev/stdout ; then
      message -n "${MESSAGE_COLOR}Summoning all spells listed in the queue..."
      message "${DEFAULT_COLOR}"
      list_install_queue
    fi
    spells_to_get=$(< $INSTALL_QUEUE)
  else 
    spells_to_get=`strip_parameters  $*`
  fi

  if [ -n "$PRINT_TYPE" ]; then
    summon_print_spells $spells_to_get
  else
    summon_spells $spells_to_get
  fi
}


. /etc/sorcery/config
if    [  "$UID"  ==  0  ] ; then
  if  [[ $NICE != "0" ]] ; then
    renice $NICE -p $$  >/dev/null
  fi
  mk_tmp_dirs summon
  main  "$@"
  rc=$?
  cleanup_tmp_dir $TMP_DIR
  exit $rc
elif  [[  $1 == -h  ]]  ||  [[  $1 == --help  ]] ; then help
else  
  echo  "Enter the root password, please."  1>&2
  PARAMS=$(consolidate_params "$@")
  su -c "$0 $PARAMS" root
fi


#---------------------------------------------------------------------
##=back
##
##=head1 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
##
#---------------------------------------------------------------------
