#!/bin/bash
#---------------------------------------------------------------------
##
##=head1 SYNOPSIS
##
##  Sorcery is a spell management utility
##
##=head1 DESCRIPTION
##
## ...
##
##=head1 COPYRIGHT
##
## Original version Copyright 2001 by Kyle Sallee
## Additions/corrections Copyright 2002 by the Source Mage Team
##
##=head1 FUNCTIONS
##
##=over 4
##
#---------------------------------------------------------------------

help() {

  cat << EOF

Sorcery is the menu interface for changing system settings, and used
for updating the system.

Example:        sorcery
Usage:          sorcery [parameters]

Optional Parameters:

-h  |  --help		Display this help screen

-s  |  system-update	Perform a system update (updates sorcery, grimoire,
			  and spells).
			  [ scribe update, sorcery queue, cast --queue ]
-u  |  update		Update the sorcery scripts only.
-g  |  upgrade		Do not update grimoire, just any spells that need to
			  be upgraded.  [ sorcery queue, cast --queue ]

-r  |  rebuild		rebuild all spells

-q  |  queue		Compare installed grimoire to installed spells,
			  generate queue of spells needing to be updated.

review-queue		Review the install queue for each spell's history 
			  since each was last installed.

hold   <spell|s>   Sets spells' status to held.
unhold <spell|s>   Sets spells' status to installed.


default add spell_1 spell_2 on/off	If "spell_1" optionally depends
					on "spell_2" the default answer
					is on/off.

default add "" spell on/off	If anything optionally depends on "spell" the
				default answer is on/off.

default add spell "" on/off	If "spell" optionally depends on anything
				the default answer is on/off.

default add spell PROVIDER on/off	"Spell" is the provder for
					PROVIDER bydefault, in the
					case of optional_depends, if
					on/off is off, none is chosen
					by default instead.

default remove [spell|""] [spell|PROVIDER|""] Remove entry from defaults
default search [spell|""] [spell|PROVIDER|""] [on|off] Search defaults

-v  | --version		Print the sorcery version

EOF

  exit 1

}

mirror_list()  {

  sort  $MIRRORS/$1 | awk '{print "\""$NF"\""; NF-- ; print $0; }'

}


select_mirror()  {

  local MIRROR_LIST=`mirror_list  $1`

  eval $DIALOG '  --title "Select Mirror Please"  \
           --ok-label  "Select"            \
           --menu                          \
           ""                              \
           0 0 0                           \
           '$MIRROR_LIST

}


mirror_menu()  {


  while

	A_HELP="Select mirror for downloading APACHE sources."
    C_HELP="Select mirror for downloading CTAN sources."
    K_HELP="Select mirror for downloading KDE sources."
    L_HELP="Select mirror for downloading kernel related sources."
    N_HELP="Select mirror for downloading GNOME sources."
    G_HELP="Select mirror for downloading GNU sources."
    S_HELP="Select mirror for downloading Sorcery itself"
   SF_HELP="Select mirror for downloading Sourceforge"
    X_HELP="Select mirror for downloading XFree86 related sources."
      HELP="Selecting a mirror site can speed your downloads."

    COMMAND=`eval $DIALOG '  --title "Mirror Menu"        \
                      --ok-label      "Select"     \
                      --cancel-label  "Exit"       \
                      --item-help                  \
                      --menu        ""  0 0 0      \
					  "APACHE"      ""  "$A_HELP"  \
                      "CTAN"        ""  "$C_HELP"  \
                      "KDE"         ""  "$K_HELP"  \
                      "KERNEL"      ""  "$L_HELP"  \
                      "GNOME"       ""  "$N_HELP"  \
                      "GNU"         ""  "$G_HELP"  \
		      "SOURCEFORGE" "" "$SF_HELP"  \
		      "SORCERY"     ""  "$S_HELP"  \
                      "XFREE86"     ""  "$X_HELP"'`
  do

    case  $COMMAND in
      APACHE)       MIRROR="      APACHE_URL"  ;;
      CTAN)         MIRROR="        CTAN_URL"  ;;
      KDE)          MIRROR="         KDE_URL"  ;;
      KERNEL)       MIRROR="      KERNEL_URL"  ;;
      GNOME)        MIRROR="       GNOME_URL"  ;;
      GNU)          MIRROR="         GNU_URL"  ;;
      SORCERY)      MIRROR="     SORCERY_URL"  ;;
      SOURCEFORGE)  MIRROR=" SOURCEFORGE_URL"  ;;
      XFREE86)      MIRROR="     XFREE86_URL"  ;;
    esac

    if  MIRROR_URL=`select_mirror  $COMMAND`;  then

      if  [  "$MIRROR_URL" == "Custom"  ];  then
         MIRROR_URL=`eval $DIALOG '  --inputbox  "Please enter the URL."  0 0'`
      fi  &&

      remove_config $LOCAL_CONFIG "$MIRROR" "$MIRROR_URL" &&
      modify_config $LOCAL_URL_CONFIG "$MIRROR" "$MIRROR_URL" &&

      eval $DIALOG  '--msgbox  "$MIRROR=$MIRROR_URL saved in $LOCAL_CONFIG" 0 0'

    fi

  done

}


show_spells()	{ (

  local  SECTION=`codex_find_section_by_name $1`
  local  SPELLS=`codex_get_spells  $SECTION`

  for  SPELL  in  $SPELLS;  do

    SPELLNAME=$( basename  $SPELL )
    if  !  spell_installed  $SPELLNAME  &&
        !  spell_held       $SPELLNAME  &&
        !  spell_exiled     $SPELLNAME
    then

      codex_set_current_spell  $SPELL
      echo  -en   '"'${SPELL:="Unknown"}'"'
      echo  -en '\t"'${VERSION:="-"}'"'
      echo  -e  '\t"'${SHORT:="Description Unavailable"}'"'

    fi

  done

) }


show_sections()  {

  LIST=`codex_get_all_section_names | sort | uniq`

  for  LINE in $LIST;  do
    echo  $LINE
    echo  "section"
  done

}


select_section() {

  eval $DIALOG  '--title "Section Selection Menu"  \
           --default-item  "$SECTION"        \
           --ok-label      "Select"          \
           --cancel-label  "Exit"            \
           --menu                            \
           ""                                \
           0 0 0                             \
           `show_sections`'

}


add_pkgs()  { (

  while

    SECTION=`select_section`

  do

    while

      SPELLS=`show_spells $SECTION`  &&
      ! [ -z "$SPELLS" ]             &&
      SPELL=`eval $DIALOG '  --title "Select spell to install please"  \
                       --item-help                               \
                       --menu                                    \
                       "$SECTION"                                \
                       0 0 0                                     \
                       '$SPELLS`

    do

      codex_set_current_spell_by_name  $SPELL
      SPELL_DESCRIPTION=`codex_get_spell_description $SPELL_DIRECTORY`

      if  eval $DIALOG  '--title      "Install $SPELL"  \
                   --yesno      "$SPELL_DESCRIPTION"    \
                   0 0'
      then

        push_install_queue  $SPELL
        eval $DIALOG  '--msgbox  "$SPELL added to the install queue."  0 0'

      else

        eval '$DIALOG  --msgbox  "$SPELL will not be installed."  0 0'

      fi
    done
  done

) }


show_file()	{

  if  [  -f  $1  ];  then

    if  [  "`file  -b  $1  |  cut  -d ' '  -f1`"  == "bzip2" ];  then
      bzcat  $1  |  $PAGER
    elif  [  "`file  -b  $1  |  cut  -d ' '  -f1`"  == "gzip" ];  then
      gzip  -cd  $1  |  $PAGER
    else
      eval $DIALOG  '--textbox  $1  0  0'
    fi

  else
    eval $DIALOG  '--msgbox  "File not found."  0  0'
    return  1
  fi

}


file_list() {

  LIST=`ls  $1`
  for  LINE  in  $LIST;  do
    echo  $LINE
    echo  `file  -b  $1/$LINE  |  cut  -d ' ' -f1`
  done

}


file_menu() {

  FILE_LIST=`file_list $1`
  echo  $1/`eval $DIALOG '  --title  "Please select a file."  \
                     --menu  "" 0 0 0                  \
                     $FILE_LIST'`

}


show_installed_spells()  {

  for  LINE  in  `sort  $SPELL_STATUS`;  do

      SPELL=`echo  "$LINE"    |  cut  -d : -f1`
     STATUS=`echo  "$LINE"    |  cut  -d : -f3`
    VERSION=`echo  "$LINE"    |  cut  -d : -f4`

    if  [  "$STATUS"  ==  "installed"  ]  ||
        [  "$STATUS"  ==  "held"       ];  then

      if  codex_set_current_spell_by_name  $SPELL;  then
        echo -en   '"'${SPELL:="Unknown"}'"'
        echo -en '\t"'${VERSION:="-"}'"'
        echo  -e '\t"'${SHORT:="Description Unavailable"}'"'
      fi

    fi
  done

}


remove_pkgs()	{

  while

    if  [  -z  "$INSTALLED_SPELLS"  ];  then
      echo  "Discovering installed spells..."
      INSTALLED_SPELLS=`show_installed_spells`
    fi

    SPELL=`eval $DIALOG '  --title "Select spell to remove please."  \
                    --item-help                               \
                    --ok-label      "Select"                  \
                    --cancel-label  "Exit"                    \
                    --menu  "" 0 0 0                          \
                    '$INSTALLED_SPELLS`

  do

    local  DESCRIPTION="Description unavailable"

    codex_set_current_spell_by_name  $SPELL
    DESCRIPTION=`codex_get_spell_description  $SPELL_DIRECTORY`

    if  $DIALOG  --title      "Remove $SPELL?"  \
                 --yesno      "$DESCRIPTION"    \
                 0 0
    then
      push_remove_queue  $SPELL                                    &&
      $DIALOG  --msgbox  "$SPELL added to the remove queue."  0 0  ||
      $DIALOG  --msgbox  "$SPELL is not really installed?"    0 0
    fi

  done

}


update_pkgs() {

  rm  -rf        $UPDATE_SCRIPT

  if  ps  -C  cast  >  /dev/null;  then
    echo    "Unable to update sorcery concurrently while casting."
    sleep   5
    return  1
  fi

  message  "${CHECK_COLOR}Updating ... please wait ... ${DEFAULT_COLOR}"

  wait_flag_up
  wait_flag $$ &

  cat  << EOF >  $UPDATE_SCRIPT
#!/bin/bash
############################################################
# Copyright 2001 by Kyle Sallee                            #
############################################################
# This helper script $UPDATE_SCRIPT is                     #
# created and executed when sorcery updates                #
############################################################

. /etc/sorcery/config

if [[ $1 == "autoupdate" ]]; then
    message  "${MESSAGE_COLOR}"
    message  "Interrupting while upgrading the sorcery scripts may"
    message  "cause the sorcery scripts to be lost.  If the sorcery,"
    message  "scripts are lost, Source Mage can be restored by"
    message  "running the following script:"
    message  "${FILE_COLOR}"
    message  "            ${RESTORE_SCRIPT}"
    message  "${MESSAGE_COLOR}"
    message  "If for some reason this does not work, see the"
    message  "Source Mage website at http://www.sourcemage.org/"
    message  "${DEFAULT_COLOR}"
    message  "${MESSAGE_COLOR}Updating grimoire...${DEFAULT_COLOR}"
    scribe update
    message  "${MESSAGE_COLOR}Ensuring sorcery-$SORCERY_BRANCH is at it's latest version...${DEFAULT_COLOR}"
    update_sorcery_scripts $SORCERY_BRANCH
fi

clean_logs
update_install_queue         # generate $INSTALL_QUEUE file
list_install_queue

message  "${MESSAGE_COLOR}Casting updated spells...${DEFAULT_COLOR}"
cast -q --queue

fix_installed_spells     # check integrity of installed spells


wait_flag_down

rm   -f  /tmp/cast

EOF


  cat  << EOF >  $RESTORE_SCRIPT
#!/bin/bash
############################################################
# This helper script /tmp/sorcery.restore can              #
# be run to restore the sorcery scripts if they            #
# are lost during a sorcery update.                        #
############################################################

echo  "Restoring the sorcery scripts, please wait ..."

SORCERY_SPOOL=${SOURCE_CACHE}
SORCERY_BRANCH=${SORCERY_BRANCH}

if [ -n $1 ]; then
  SORCERY_BRANCH=$1
fi

if  cd /tmp                                                 &&
    bunzip2 -c $SORCERY_SPOOL/sorcery-$SORCERY_BRANCH.tar.bz2 | tar xf - &&
    cd sorcery                                              &&
  ./install;                                              then
  rm -rf /tmp/sorcery
  echo  "Sorcery was successfully restored."
else
  echo  "Unable to restore sorcery.  Try running this file with"
  echo  "the name of the branch you had previously installed as"
  echo  "the command-line parameter: (e.g. stable, or devel)."
  echo
  echo  "For more help, see the Source Mage website "
  echo  "(http://www.sourcemage.org/)."
fi

EOF

  chmod  100     $RESTORE_SCRIPT
  chmod  100     $UPDATE_SCRIPT
  exec           $UPDATE_SCRIPT  $1

}


update_sorcery () {

  cat  << EOF >  $RESTORE_SCRIPT
#!/bin/bash
############################################################
# This helper script /tmp/sorcery.restore can              #
# be run to restore the sorcery scripts if they            #
# are lost during a sorcery update.                        #
############################################################

echo  "Restoring the sorcery scripts, please wait ..."

SORCERY_SPOOL=${SOURCE_CACHE}
SORCERY_BRANCH=${SORCERY_BRANCH}

if [ -n $1 ]; then
  SORCERY_BRANCH=$1
fi

if  cd /tmp                                                 &&
    bunzip2 -c $SORCERY_SPOOL/sorcery-$SORCERY_BRANCH.tar.bz2 | tar xf - &&
    cd sorcery                                              &&
  ./install;                                              then
  rm -rf /tmp/sorcery
  echo  "Sorcery was successfully restored."
else
  echo  "Unable to restore sorcery.  Try running this file with"
  echo  "the name of the branch you had previously installed as"
  echo  "the command-line parameter: (e.g. stable, or devel)."
  echo
  echo  "For more help, see the Source Mage website "
  echo  "(http://www.sourcemage.org/)."
fi

EOF

    message  "${MESSAGE_COLOR}"
    message  "Interrupting while upgrading the sorcery scripts may"
    message  "cause the sorcery scripts to be lost.  If the sorcery,"
    message  "scripts are lost, Source Mage can be restored by"
    message  "running the following script:"
    message  "${FILE_COLOR}"
    message  "            bash ${RESTORE_SCRIPT}"
    message  "${MESSAGE_COLOR}"
    message  "If for some reason this does not work, see the"
    message  "Source Mage website at http://www.sourcemage.org/"
    message  "${DEFAULT_COLOR}"

    update_sorcery_scripts $SORCERY_BRANCH

}


update_queue () {
    update_install_queue
    list_install_queue
}

rebuild()  {

  rm  -rf  $INSTALL_QUEUE

  message  "To do a non recursive rebuild"
  message  "all installed spells must be fixed first."
  sleep  3
  cleanse --fix

  for  LINE  in  `cat  $SPELL_STATUS`;  do
      SPELL=`echo  "$LINE"  |  cut  -d : -f1`
     STATUS=`echo  "$LINE"  |  cut  -d : -f3`
    SECTION=`find_section  $SPELL`
    if  [  "$STATUS"   ==  "installed"  ]   &&
        [  "$SECTION"  !=  "sgl"        ]   &&
        [  "$SECTION"  !=  "sections"   ]   &&
	! spell_exiled $SPELL           ;  then
      echo  $SPELL  >>  $INSTALL_QUEUE
    fi
  done

  unset  SPELL
  cast --queue

#Taken care of cast --queue now:
#  if    query  "Edit Rebuild/Install Queue?" n
#  then  edit_file  $INSTALL_QUEUE
#  fi
#  cast --compile  `cat  $INSTALL_QUEUE`
#  rm                      $INSTALL_QUEUE

}


make_checklist()  {


  local  SECTION=`codex_find_section_by_name  $1`
  local   SPELLS=`codex_get_spells  $SECTION`

  for  SPELL in $SPELLS;  do

    if  codex_set_current_spell  $SPELL;  then

      STATUS="OFF"

      if    spell_installed  $SPELL  ||
            spell_held       $SPELL
      then  STATUS="on"
      else  STATUS="off"
      fi

      echo -en   '"'${SPELL:="Unknown"}'"'
      echo -en '\t"'${VERSION:="-"}'"'
      echo -en '\t"'$STATUS'"'
      echo -e  '\t"'${SHORT:="Description Unavailable"}'"'

    fi

  done

}


process_section()  {

  local    SECTION=`codex_find_section_by_name $1`
  local  KEEP_LIST=$2
  local     SPELLS=`ls  $GRIMOIRE/$SECTION`

  for  SPELL  in  $SPELLS;  do

    LINE=$( basename  $SPELL )
    if  echo  -e  "$KEEP_LIST"  |
        grep  -q  "^$LINE\$"
    then  push_install_queue  $LINE
    else  push_remove_queue   $LINE
    fi

  done

}


select_pkgs()  {

  SELECT_TITLE="Spell Toggle Selection Menu"
  SELECT_HELP="[X]=install  [ ]=remove"

  while  SECTION=`select_section`;  do

    CHECKLIST=`make_checklist  $SECTION`

    if  OUTLIST=`eval $DIALOG '  --title "$SELECT_TITLE"   \
                          --ok-label  "Commit"      \
                          --item-help               \
                          --separate-output         \
                          --checklist               \
                          "$SELECT_HELP  $SECTION"  \
                          0 0 0                     \
                          '$CHECKLIST`

    then  process_section  "$SECTION"  "$OUTLIST"
    fi
  done

}


make_hold_checklist()  {

  array=()

  for  LINE in `sort  $SPELL_STATUS`;  do

    explode "$LINE" ":" "array"

      SPELL="${array[0]}"
     STATUS="${array[2]}"
    VERSION="${array[3]}"

    if  [  "$STATUS"  ==  "installed"  ]   ||
        [  "$STATUS"  ==  "held"       ];  then

      [  "$STATUS"  ==  "held"  ]  &&
      HELD="on"                    ||
      HELD="off"

      if  codex_set_current_spell_by_name  $SPELL;  then

        echo  -en   "\"${SPELL:="Unknown"}\""
        echo  -en "\t\"${VERSION:="-"}\""
        echo  -en "\t\"$HELD\""
        echo  -e  "\t\"${SHORT:="Description Unavailable"}\""

      fi
    fi
  done

}


hold_pkgs()  {

  local array=()
  local tSPELL_STATUS

  CHECKLIST=`make_hold_checklist`

  HOLD_TITLE="Select spells to hold or unhold"
   HOLD_HELP="[X]=held  [ ]=installed"

  if  OUTLIST=`eval $DIALOG '  --title "$HOLD_TITLE"  \
                        --item-help            \
                        --ok-label  "Commit"   \
                        --separate-output      \
                        --checklist            \
                        "$HOLD_HELP"           \
                        0 0 0                  \
                        '$CHECKLIST`
  then
        set_unheld $(get_held)
        set_held   $OUTLIST
  fi

}


spell_menu() {

  while

    U_HELP="Current software hinders crackers' attempts to infiltrate your box"
    S_HELP="Install and remove multiple spells from a section using a single
selection"
    A_HELP="Simple safe, verbose way of selecting spells for installation"
    R_HELP="Simple safe, verbose way of selecting spells for removal"
    B_HELP="Rebuild all installed spells"
    H_HELP="Held spells will not be upgraded until unheld or broken"
    E_HELP="Done managing spells"
     TITLE="Spell Menu"
        OK="Select"
    CANCEL="Exit"

    COMMAND=`eval $DIALOG '  --title "$TITLE"           \
                      --item-help                \
                      --ok-label      "$OK"      \
                      --cancel-label  "$CANCEL"  \
                      --menu  ""  0 0 0          \
                      "A"  "Add"      "$A_HELP"  \
                      "B"  "Rebuild"  "$B_HELP"  \
                      "H"  "Hold"     "$H_HELP"  \
                      "R"  "Remove"   "$R_HELP"  \
                      "S"  "Select"   "$S_HELP"  \
                      "U"  "Update"   "$U_HELP"'`
  do

    case  $COMMAND in
      U)  ( sorcery    system-update; ) ;;
      S)  select_pkgs  ;;
      A)  add_pkgs     ;;
      R)  remove_pkgs  ;;
      B)  rebuild      ;;
      H)  hold_pkgs    ;;
      E)  break        ;;
    esac

  done

}


grep_install_logs() {

  if  WHAT=`eval $DIALOG '  --inputbox                                \
                    "Please enter full path and name of file"  \
                    0 0'`
  then
    cd  $INSTALL_LOGS
    grep  "$WHAT\$"  *  | $PAGER
  fi

}


optimize_architecture()  {

  architecture_menu  ARCHITECTURE  "Build system selection"
  if [[ $CROSS_INSTALL == on ]]; then
    architecture_menu  TARGET      "Target system selection"
  fi
  optimization_menu

}

architecture_menu() {

  debug "sorcery" "architecture_menu()"
  local  SPECFILE
  local  LIST
  for  SPECFILE  in  `find  $ARCH_SPECS  -not  -name '*~' | sort`; do
    if  [[  -x  $SPECFILE  ]]  &&
        grep  -q  "CPUNAME"  $SPECFILE; then
      local CPUNAME=""
      CPUNAME=$( .  $SPECFILE  &&  echo $CPUNAME )  &&
      LIST="$LIST
\"`basename $SPECFILE`\"	\"$CPUNAME\"	\"$CPUNAME\""
    fi
  done
  debug  "sorcery" "architecture_menu() - Dialog options are $LIST"

  local ARCH_TITLE="$2"
  local ARCH_HELP="Please select a microprocessor category"

  if   ARCHITECTURE=`eval $DIALOG '  --title  "$ARCH_TITLE"     \
                              --item-help                \
                              --no-cancel                \
                              --menu                     \
                              "$ARCH_HELP"               \
                               0 0 0                     \
			       '$LIST              `; then

    debug "sorcery" "architecture_menu() - ARCHITECTURE='$ARCHITECTURE'"

    modify_local_config "$1" "$ARCHITECTURE"

  fi


}

optimization_menu(){

  local OPTIMIZATIONS
  local      OPT_TITLE="Optimization Menu"
  local       OPT_HELP="Please select optimizations"

  local COMBRELOC_HELP="Speed up loading libs, also needed for prelink (LDFLAGS=-z combreloc)"
  local   PRELINK_HELP="Speed up loading applications by pre-linking libraries (CFLAGS=-DPIC -fPIC)"
  local     RISKY_HELP="Optimize by violating ANSI/IEEE (unsafe) (CFLAGS=-ffast-math -funroll-loops)"
  local    SPEEDY_HELP="Optimize generated code, conflicts with 'tiny' (CFLAGS=$FAST)"
  local    STATIC_HELP="Compile libraries statically (LDFLAGS=-static)"
  local     STRIP_HELP="Remove all symbol table and relocation (debugging) information (LDFLAGS=-s)"
  local      TINY_HELP="Optimize to smaller generated code, conflicts with 'speedy' (CFLAGS=$SMALL)"

  if  OPTIMIZATIONS=`eval $DIALOG '  --title  "$OPT_TITLE"     \
                              --no-cancel               \
                              --item-help               \
                              --separate-output         \
                              --checklist               \
                              "$OPT_HELP"               \
                               0 0 0                    \
        "combreloc" "         ++speed"  "$COMBRELOC" "$COMBRELOC_HELP" \
        "prelink"   "          +speed"  "$PRELINK"   "$PRELINK_HELP"   \
        "risky"     "          +speed"  "$RISKY"     "$RISKY_HELP"     \
        "speedy"    "  +size  ++speed"  "$SPEEDY"    "$SPEEDY_HELP"    \
        "static"    " ++size   +speed"  "$STATIC"    "$STATIC_HELP"    \
        "strip"     " --size"           "$STRIP"     "$STRIP_HELP"     \
        "tiny"      "  -size   +speed"  "$TINY"      "$TINY_HELP"'`
  then

    OPTIMIZATIONS=`echo  ${OPTIMIZATIONS}  |  tr  '\n'  ' '`
    debug "sorcery" "optimization_menu() - OPTIMIZATIONS='${OPTIMIZATIONS}'"

    modify_local_config "OPTIMIZATIONS" "$OPTIMIZATIONS"

  fi
}


integrity_fix_menu()  {

    INT_TITLE="Integrity Checking Selection Menu"
     INT_HELP="Please select the tests which cleanse --fix should execute."
    FIND_HELP="Discover missing  binary executables, libraries, and header files"
     LDD_HELP="Discover broken   binary executables, and libraries"
     SYM_HELP="Discover misowned symbolic links to files"
  MD5SUM_HELP="Discover modified binary executables, and libraries"

  if  INT_FIX_CHECKS=`eval $DIALOG '  --title  "$INT_TITLE"  \
                           --no-cancel            \
                           --item-help            \
                           --separate-output      \
                           --checklist            \
                           "$INT_HELP"            \
                           0 0 0                  \
        "FIND_CHECK"    ""  "$FIND_CHECK"    "$FIND_HELP"    \
        "MD5SUM_CHECK"  ""  "$MD5SUM_CHECK"  "$MD5SUM_HELP"  \
        "LDD_CHECK"     ""  "$LDD_CHECK"     "$LDD_HELP"     \
        "SYM_CHECK"     ""  "$SYM_CHECK"     "$SYM_HELP"'`
  then

        FIND_CHECK=off
      MD5SUM_CHECK=off
         LDD_CHECK=off
         SYM_CHECK=off

    for  CHECK  in  $INT_FIX_CHECKS;  do
      case  $CHECK  in
          FIND_CHECK)    FIND_CHECK=on  ;;
        MD5SUM_CHECK)  MD5SUM_CHECK=on  ;;
           LDD_CHECK)     LDD_CHECK=on  ;;
           SYM_CHECK)     SYM_CHECK=on  ;;
      esac
    done

    modify_local_config "FIND_CHECK" "$FIND_CHECK"
    modify_local_config "MD5SUM_CHECK" "$MD5SUM_CHECK"
    modify_local_config "LDD_CHECK" "$LDD_CHECK"
    modify_local_config "SYM_CHECK" "$SYM_CHECK"

  fi

}


integrity_download_menu()  {

     INT_DL_TITLE="Archive Integrity Checking Level Menu"
      INT_DL_HELP="On bad archive integrity checks:
c = continue, a = abort, n = ask default abort no,
y = ask default abort yes, - = doesn't get checked, continues.
K MD5SUM_DL . good bad IGNORE missing
- ----------- ---- --- ------ -------
P all_abort . . c . a . . a . . . a .
A on|*. . . . . c . a . . y . . . a .
B ask_abort . . c . y . . y . . . y .
U ask_risky . . c . y . . n . . . y .
G ask_ignore. . c . n . . n . . . n .
I off . . . . . - . - . . - . . . - .
"
   ABORT_ALL_HELP="Abort use of the file. Do not prompt. Period. PARANOID"
       ABORT_HELP="Abort use of the file. Do not prompt unless the MD5 is set to IGNORE. SAFER"
   ABORT_ASK_HELP="Ask, but default to abort. SAFE"
   ABORT_IGN_HELP="Ask, but default to abort unless the MD5 is set to IGNORE. RISKY"
  IGNORE_ASK_HELP="Ask, but default to ignore. UNSAFE"
      IGNORE_HELP="Ignore (do not check) integrity of downloads. DANGEROUS!"

  if  INT_DL_CHECK=`eval $DIALOG '  --title  "$INT_DL_TITLE"        \
   			     --no-cancel                            \
			     --ok-label    "Commit"                 \
			     --item-help                            \
			     --menu                                 \
			     "$INT_DL_HELP"                         \
			     0 0 0                                  \
	"P"  "Abort unpack paranoid"             "$ABORT_ALL_HELP"  \
	"A"  "Abort unpack but ask on ignore"    "$ABORT_HELP"      \
	"B"  "Ask (default abort)"               "$ABORT_ASK_HELP"  \
	"U"  "Ask (default abort save ignore)"   "$ABORT_IGN_HELP"  \
	"G"  "Ask (default ignore)"              "$IGNORE_ASK_HELP" \
	"I"  "Ignore (do not check)"             "$IGNORE_HELP"'`
  then
    case $INT_DL_CHECK in
      P) modify_local_config "MD5SUM_DL" "abort_all" ;;
      A) modify_local_config "MD5SUM_DL" "on" ;;
      B) modify_local_config "MD5SUM_DL" "ask_abort" ;;
      U) modify_local_config "MD5SUM_DL" "ask_risky" ;;
      G) modify_local_config "MD5SUM_DL" "ask_ignore" ;;
      I) modify_local_config "MD5SUM_DL" "off" ;;
    esac
  fi

}


integrity_menu()  {

  INT_TITLE="Integrity Checking Selection Menu"
   INT_HELP="Options involving integrity checking, including --fix and download options."
   FIX_HELP="Set cleanse --fix checks"
    DL_HELP="Discover corrupted or modified archives during cast"

  while  INT_CHECKS=`eval $DIALOG '  --title  "$INT_TITLE"    \
                           --cancel-label  "Exit"      \
			   --ok-label      "Select"    \
                           --item-help                 \
                           --menu                      \
                           "$INT_HELP"                 \
                           0 0 0                       \
        "F"  "System integrity"   "$FIX_HELP"          \
        "D"  "Download integrity" "$DL_HELP"'`
  do
    case $INT_CHECKS in
      F)  integrity_fix_menu       ;;
      D)  integrity_download_menu  ;;
    esac
  done

}

set_email()  {

  if  SORCERER=`eval $DIALOG '  --ok-label  "Commit"         \
                         --inputbox                   \
                "Please enter the email address of the person or role account
that should receive reports from this box."  \
                0 0  "$SORCERER"'`
  then

    modify_local_config "SORCERER" "$SORCERER"

  fi

}


#---------------------------------------------------------------------
##=item sorcery_set_jobs
##
## Brings up a dialog that allows administrator to choose the number
## of processes that make should use.  If the user selects "Commit",
## the MAKE_NJOBS variable is written to the local config file.
##
#  Created by Eric Sandall <sandalle@yahoo.com>  2002-06-28@00:08 PST
#---------------------------------------------------------------------
sorcery_set_jobs() {
  [  -z  "$MAKE_NJOBS"  ]  &&  MAKE_NJOBS=1

  local MAKE_NJOBS_HELP="Enter the number of jobs 'make' should run at the     \
                         same time.  WARNING: Anything greater than 1 is risky \
                         as not all makefiles support concurrent builds."

  if  MAKE_NJOBS=`eval $DIALOG '  --ok-label  "Commit"  \
                           --inputbox            \
                           "$MAKE_NJOBS_HELP"      \
                           0 0  "$MAKE_NJOBS"'`
  then

    TEMP=`cat       $LOCAL_COMPILE_CONFIG  |
          grep -v   "MAKE_NJOBS="`
    echo  "$TEMP"                   >       $LOCAL_COMPILE_CONFIG
    echo  "MAKE_NJOBS=$MAKE_NJOBS"  >>      $LOCAL_COMPILE_CONFIG
  fi
}


#---------------------------------------------------------------------
##=item sorcery_distcc
##
## Allows the admin to set which hosts are compile volunteers.
##
#---------------------------------------------------------------------

sorcery_distcc() {

  [  -z  "$DISTCC_HOSTS"  ]  &&  DISTCC_HOSTS=""

  local DISTCC_HELP="Enter space separated list of volunteers. Leave empty to \
                     disable distributed compilation. Number of make jobs is  \
                     automatically altered to the number of volunteers plus one"

  if  DISTCC_HOSTS=`eval $DIALOG '  --ok-label  "Commit"  \
                             --inputbox                   \
                             "$DISTCC_HELP"               \
                             0 0 "$DISTCC_HOSTS"'`
  then
    TEMP=`cat       $LOCAL_COMPILE_CONFIG  |
          grep  -v  "DISTCC_HOSTS="        |
          grep  -v  "MAKE_NJOBS="`

    echo  "$TEMP"                               >   $LOCAL_COMPILE_CONFIG
    echo  "DISTCC_HOSTS=\"$DISTCC_HOSTS\""      >>  $LOCAL_COMPILE_CONFIG

    explode "$DISTCC_HOSTS" " " "hosts"
    echo  "MAKE_NJOBS=$(( ${#hosts[@]} + 1 ))"  >>  $LOCAL_COMPILE_CONFIG
    unset hosts
  fi

}


set_branch() {


  while

    D_HELP="Nightly devel snapshots"
    T_HELP="Current release candidate or stable release"
    S_HELP="Current stable version"
    C_HELP="Choose a custom version"

    COMMAND=`eval $DIALOG '  --title "Currently tracking : $SORCERY_BRANCH "  \
                      --item-help                               \
                      --ok-label      "Select"                  \
                      --cancel-label  "Exit"                    \
                      --menu                                    \
                      ""                                        \
                      0 0 0                                     \
                      "S"  "Stable Branch"            "$S_HELP" \
                      "T"  "Test Branch"              "$T_HELP" \
                      "D"  "Devel Branch"             "$D_HELP" \
                      "C"  "Custom Branch"             "$C_HELP"'`

  do

    case  $COMMAND in

      S)  modify_local_config "SORCERY_BRANCH" "stable"  &&
          SORCERY_BRANCH="stable"                        ;;
      T)  modify_local_config "SORCERY_BRANCH" "test"    &&
          SORCERY_BRANCH="test"                          ;;
      D)  modify_local_config "SORCERY_BRANCH" "devel"   &&
          SORCERY_BRANCH="devel"                         ;;
      C)  set_custom_branch                              ;;

    esac

  done

}

set_custom_branch() {


  while

    C_HELP="Please choose the sorcery release/version you want to use, this can be anything you want from download.sourcemage.org/sorcery/sorcery-<version>.tar.bz2"

    COMMAND=`eval $DIALOG '  --title "Currently tracking : $SORCERY_BRANCH "  \
                      --item-help                               \
                      --ok-label      "Select"                  \
                      --cancel-label  "Exit"                    \
                      --inputbox                                \
                      "$C_HELP"                                 \
                      0 0                                       \
                      "$SORCERY_BRANCH"'`

   do

     modify_local_config "SORCERY_BRANCH" "$COMMAND"   &&
     SORCERY_BRANCH="$COMMAND"

  done


}



set_delay()  {

  if  PROMPT_DELAY=`eval $DIALOG '  --ok-label  "Commit"  \
                             --inputbox            \
                             "Please enter the time in seconds to wait for a response when prompted with a question."  \
                              0 0  "$PROMPT_DELAY"'`
  then

    modify_local_config "PROMPT_DELAY" "$PROMPT_DELAY"

  fi

}


set_download_rate()  {

  PROMPT="Please enter the maximum bytes per second for summoning"

  if  DOWNLOAD_RATE=`eval $DIALOG '  --ok-label  "Commit"  \
                              --inputbox            \
                              "$PROMPT"             \
                               0 0  "$DOWNLOAD_RATE"'`
  then

    modify_local_config "DOWNLOAD_RATE" "$DOWNLOAD_RATE"

  fi

}

set_http_ftp_timeout()  {

	PROMPT="Please enter maximum time (seconds) summon is to wait for each download server"

	if  URL_HTTP_FTP_TIMEOUT=`eval $DIALOG '  --ok-label  "Commit"  \
                                            --inputbox            \
                                            "$PROMPT"             \
                                            0 0  "$URL_HTTP_FTP_TIMEOUT"'`
	then

		modify_local_config "URL_HTTP_FTP_TIMEOUT" "$URL_HTTP_FTP_TIMEOUT"

	fi

}

queue_menu()  {

  while

    I_HELP="View the list of spells selected for installation"
    i_HELP="Edit the list of spells selected for installation"
    R_HELP="View the list of spells selected for removal"
    r_HELP="Edit the list of spells selected for removal"
    S_HELP="View the datafile of installed spells"
    s_HELP="Edit the datafile of installed spell"

    COMMAND=`eval $DIALOG '  --title "Queue Menu"                           \
                      --ok-label      "Select"                       \
                      --cancel-label  "Exit"                         \
                      --default-item  $COMMAND                       \
                      --item-help                                    \
                      --menu                                         \
                      ""                                             \
                      0 0 0                                          \
                      "I"     "View     install  queue"   "$I_HELP"  \
                      "i"     "Edit     install  queue"   "$i_HELP"  \
                      "R"     "View     removal  queue"   "$R_HELP"  \
                      "r"     "Edit     removal  queue"   "$r_HELP"  \
                      "S"     "View     spell    status"  "$S_HELP"  \
                      "s"     "Edit     spell    status"  "$s_HELP"'`

  do

    case  $COMMAND in

      S)  show_file  $SPELL_STATUS         ;;
      s)  edit_file  $SPELL_STATUS         ;;
      I)  show_file  $INSTALL_QUEUE        ;;
      i)  edit_file  $INSTALL_QUEUE        ;;
      R)  show_file  $REMOVE_QUEUE         ;;
      r)  edit_file  $REMOVE_QUEUE         ;;

    esac

  done

}


log_menu()  {

  while

    C_HELP="View compile logs of previously installed software"
    G_HELP="Discover a file's origin"
    I_HELP="View logs of files previously installed"
    c_HELP="Remove a compile log"
    i_HELP="Edit a log of files previously installed"

    COMMAND=`eval $DIALOG '  --title "Log Menu"                          \
                      --ok-label      "Select"                    \
                      --cancel-label  "Exit"                      \
                      --default-item  $COMMAND                    \
                      --item-help                                 \
                      --menu                                      \
                      ""                                          \
                      0 0 0                                       \
                      "G"     "Grep    install logs"  "$G_HELP"   \
                      "I"     "View    install log"   "$I_HELP"   \
                      "i"     "Edit    install log"   "$i_HELP"   \
                      "C"     "View    compile log"   "$C_HELP"   \
                      "c"     "Remove  compile log"   "$c_HELP"'`

  do

    case  $COMMAND in

      G)  grep_install_logs                      ;;
      I)  show_file  `file_menu  $INSTALL_LOGS`  ;;
      i)  edit_file  `file_menu  $INSTALL_LOGS`  ;;
      C)  show_file  `file_menu  $COMPILE_LOGS`  ;;
      c)  rm         `file_menu  $COMPILE_LOGS`  ;;

    esac

  done

}

sorcery_devel_settings()   {

  while

    D_HELP="Set the debugging file for normal debugging."
	S_HELP="Turn on Super Debug. You probably don't want to do this."

	COMMAND=`eval $DIALOG '--title      "Sorcery Development"		\
						--ok-label      "Select"					\
						--cancel-label  "Exit"						\
						--default-item  $COMMAND					\
						--item-help									\
						--menu										\
						""											\
						0 0 0										\
						"D"  "Debug file"				"$D_HELP"	\
						"S"  "Super debugging toggle"	"$S_HELP"'`
  do

    case $COMMAND in

	  D) TEXT="Note: if you turn this on, don't forget to empty the log file occasionaly.\nWhat file do you want the debugging logged to?"
	  		FILE=`eval $DIALOG --ok-label "Commit" --inputbox \"$TEXT\" 0 0 \"$DEBUG\"` &&
	  		modify_local_config "DEBUG" "$FILE" ;;
	  S) TEXT="Note: You don't want to do this probably. Don't forget to 2>/root/debug.out.\nDo you want super debugging on?"
	  		TOGGLE=`eval $DIALOG --yesno \"$TEXT\" 0 0` &&
	  		( modify_local_config "SUPER_DEBUG" "on" ; modify_local_config "set" "-x" "command" ) ||
			( modify_local_config "SUPER_DEBUG" ""   ; modify_local_config "set" "+x" "command" ) ;;

	esac

  done

}


feature_menu()  {

  B_HELP="Administrate groups of Unix/Linux boxes?"
  C_HELP="Colorized messages on cast and dispel?"
  D_HELP="Automatically gather miscellaneous documentation from spells"
  E_HELP="Remove files when dispelling?"
  F_HELP="Check for and repair broken programs after updating sorcery?"
  G_HELP="Slower initial compilation, accelerated upgrade compilation?"
  I_HELP="Create archives of installed software?"
  L_HELP="Locally customize SPELL configuration?"
  M_HELP="Email reports?"
  P_HELP="Preserve modified files or backup them up and overwrite with defaults?"
  R_HELP="Prompt to view reports?"
TMP_HELP="Attempt to compile entirely in RAM?"
  T_HELP="Disallow dispelling of spells that would cause terrible malfunctions?"
  U_HELP="Automatically remove old sources and install caches upon sorcery update?"
  V_HELP="View compilation as it happens?"
 NS_HELP="Use netselect to try fastest mirrors first if netselect is available?"
 CS_HELP="Clean up source directories after failures?"
 CI_HELP="Non-native installation / cross compilation"
 ST_HELP="Set xterm title/screen window title on cast?"
 UF_HELP="Ensure a sane environment before sorcery update"

       ARCHIVE=${ARCHIVE:=on}
       AUTOFIX=${AUTOFIX:=on}
     UPDATEFIX=${UPDATEFIX:=off}
     AUTOPRUNE=${AUTOPRUNE:=off}
         CABAL=${CABAL:=off}
        CCACHE=${CCACHE:=off}
         COLOR=${COLOR:=on}
    CONFIG_LOC=${CONFIG_LOC:=on}
   GATHER_DOCS=${GATHER_DOCS:=on}
  MAIL_REPORTS=${MAIL_REPORTS:=off}
         TMPFS=${TMPFS:=on}
  VIEW_REPORTS=${VIEW_REPORTS:=off}
      PRESERVE=${PRESERVE:=on}
       SUSTAIN=${SUSTAIN:on}
        VOYEUR=${VOYEUR:=on}
          REAP=${REAP:=on}
    NET_SELECT=${NET_SELECT:=off}
  CLEAN_SOURCE=${CLEAN_SOURCE:=off}
 CROSS_INSTALL=${CROSS_INSTALL:=off}
SET_TERM_TITLE=${SET_TERM_TITLE:=off}

  if  TOGGLES=`eval $DIALOG '  --title "Feature Menu"  \
                        --no-cancel             \
                        --item-help             \
                        --separate-output       \
                        --checklist             \
                        ""                      \
                        0 0 0                   \
      "ARCHIVE"        "Toggle"  "$ARCHIVE"        "$I_HELP"   \
      "AUTOFIX"        "Toggle"  "$AUTOFIX"        "$F_HELP"   \
      "UPDATEFIX"      "Toggle"  "$UPDATEFIX"      "$UF_HELP"   \
      "AUTOPRUNE"      "Toggle"  "$AUTOPRUNE"      "$U_HELP"   \
      "CABAL"          "Toggle"  "$CABAL"          "$B_HELP"   \
      "CCACHE"         "Toggle"  "$CCACHE"         "$G_HELP"   \
      "COLOR"          "Toggle"  "$COLOR"          "$C_HELP"   \
      "CONFIG_LOC"     "Toggle"  "$CONFIG_LOC"     "$L_HELP"   \
      "GATHER_DOCS"    "Toggle"  "$GATHER_DOCS"    "$D_HELP"   \
      "MAIL_REPORTS"   "Toggle"  "$MAIL_REPORTS"   "$M_HELP"   \
      "PRESERVE"       "Toggle"  "$PRESERVE"       "$P_HELP"   \
      "SUSTAIN"        "Toggle"  "$SUSTAIN"        "$T_HELP"   \
      "TMPFS"          "Toggle"  "$TMPFS"          "$TMP_HELP" \
      "VIEW_REPORTS"   "Toggle"  "$VIEW_REPORTS"   "$R_HELP"   \
      "VOYEUR"         "Toggle"  "$VOYEUR"         "$V_HELP"   \
      "REAP"           "Toggle"  "$REAP"           "$E_HELP"   \
      "NET_SELECT"     "Toggle"  "$NET_SELECT"     "$NS_HELP"  \
      "CLEAN_SOURCE"   "Toggle"  "$CLEAN_SOURCE"   "$CS_HELP"  \
      "CROSS_INSTALL"  "Toggle"  "$CROSS_INSTALL"  "$CI_HELP"  \
      "SET_TERM_TITLE" "Toggle"  "$SET_TERM_TITLE" "$ST_HELP"'`
  then
    TEMP=(ARCHIVE AUTOFIX AUTOPRUNE CABAL COLOR GATHER_DOCS MAIL_REPORTS VIEW_REPORTS PRESERVE SUSTAIN TMPFS VOYEUR REAP NET_SELECT CONFIG_LOC CLEAN_SOURCE CROSS_INSTALL SET_TERM_TITLE)
    for i in ${TEMP[*]} ; do
      eval $i=off
    done

    for  TOGGLE  in  $TOGGLES;  do

      case  $TOGGLE  in

             ARCHIVE)        ARCHIVE=on  ;;
             AUTOFIX)        AUTOFIX=on  ;;
           UPDATEFIX)      UPDATEFIX=on  ;;
           AUTOPRUNE)      AUTOPRUNE=on  ;;
               CABAL)          CABAL=on  ;;
              CCACHE)         CCACHE=on  ;;
               COLOR)          COLOR=on  ;;
          CONFIG_LOC)     CONFIG_LOC=on  ;;
         GATHER_DOCS)    GATHER_DOCS=on  ;;
        MAIL_REPORTS)   MAIL_REPORTS=on  ;;
            PRESERVE)       PRESERVE=on  ;;
             SUSTAIN)        SUSTAIN=on  ;;
               TMPFS)          TMPFS=on  ;;
        VIEW_REPORTS)   VIEW_REPORTS=on  ;;
              VOYEUR)         VOYEUR=on  ;;
                REAP)           REAP=on  ;;
          NET_SELECT)     NET_SELECT=on  ;;
        CLEAN_SOURCE)   CLEAN_SOURCE=on  ;;
       CROSS_INSTALL)  CROSS_INSTALL=on  ;;
      SET_TERM_TITLE) SET_TERM_TITLE=on  ;;
      esac

    done

    TEMP=(ARCHIVE AUTOFIX UPDATEFIX AUTOPRUNE CABAL GATHER_DOCS MAIL_REPORTS VIEW_REPORTS PRESERVE SUSTAIN TMPFS VOYEUR REAP NET_SELECT CONFIG_LOC CLEAN_SOURCE CROSS_INSTALL SET_TERM_TITLE)
    for i in ${TEMP[*]} ; do
      modify_local_config "$i" "${!i}"
    done

    # reset of install root needed if CROSS_INSTALL turned off
    # or can't find spells! ;-)
    modify_local_config "INSTALL_ROOT" ""
    modify_local_config "color" "$COLOR" "command"

    TEMP=`cat       $LOCAL_COMPILE_CONFIG  |
          grep  -v  "CCACHE="`

    echo  "$TEMP"           >   $LOCAL_COMPILE_CONFIG
    echo  "CCACHE=$CCACHE"  >>  $LOCAL_COMPILE_CONFIG
  fi

}

option_menu()  {

  while

    B_HELP="Specify the sorcery branch you would like to track"
    H_HELP="Specify the color scheme for messages"
    D_HELP="Enter the default delay time for prompts"
    E_HELP="Enter the email address for this box's sorcerer"
    F_HELP="Select many options on or off at once"
    M_HELP="Select ftp and http mirrors for faster downloads"
    O_HELP="Select architecture optimizations"
    I_HELP="Select the test that cleanse --fix, and AUTOFIX execute"
    J_HELP="Enter the number of jobs 'make' should run at the same time"
    C_HELP="Setup distributed compilation"
    R_HELP="Enter the maximum rate for downloading"
    T_HELP="Select compression program for logs and archives"
    N_HELP="Enter the process priority (nice value) to use for sorcery"
    S_HELP="Sorcery development options (debugging)"
    W_HELP="Enter maximum timeout (seconds) for summoning sources"
    Z_HELP="Select sorcery sound scheme"


    COMMAND=`eval $DIALOG '  --title "Option Menu"              \
                      --item-help                               \
                      --ok-label      "Select"                  \
                      --cancel-label  "Exit"                    \
                      --menu                                    \
                      ""                                        \
                      0 0 0                                     \
                      "B"  "Sorcery Branch"           "$B_HELP" \
                      "H"  "Color Scheme"             "$H_HELP" \
                      "D"  "Prompt Delay"             "$D_HELP" \
                      "R"  "Download Rate"            "$R_HELP" \
                      "N"  "Nice Level"               "$N_HELP" \
                      "E"  "Email of Sorcerer"        "$E_HELP" \
                      "F"  "Feature Menu"             "$F_HELP" \
                      "I"  "Integrity Checking"       "$I_HELP" \
                      "J"  "Number of \"make\" Jobs"  "$J_HELP" \
                      "C"  "Distributed compilation"  "$C_HELP" \
                      "M"  "Software Mirrors"         "$M_HELP" \
                      "O"  "Optimize Architecture"    "$O_HELP" \
                      "T"  "Compression Type"         "$T_HELP" \
                      "S"  "Sorcery Development"      "$S_HELP" \
                      "W"  "Summon Timeout Value"     "$W_HELP" \
                      "Z"  "Select Sound Scheme"      "$Z_HELP"'`

  do

    case  $COMMAND in

      B)  set_branch             ;;
      H)  color_schemes_menu     ;;
      D)  set_delay              ;;
      R)  set_download_rate      ;;
      N)  set_nice               ;;
      E)  set_email              ;;
      F)  feature_menu           ;;
      I)  integrity_menu         ;;
      J)  sorcery_set_jobs       ;;
      C)  sorcery_distcc         ;;
      M)  mirror_menu            ;;
      O)  optimize_architecture  ;;
      S)  sorcery_devel_settings ;;
      T)  set_compression_type   ;;
      W)  set_http_ftp_timeout   ;;
      Z)  sound_schemes_menu     ;;

    esac

  done

}


goodbye() {

  echo  "Have a sorcerous day."
  exit

}


background_execute() {

  $DIALOG  --msgbox  "Processing queues in the background."  0 0

  [  -f         $REMOVE_QUEUE  ]  &&
  dispel  `cat  $REMOVE_QUEUE`   1>/dev/null 2>&1
  rm  -f        $REMOVE_QUEUE

  if  [  -f             $INSTALL_QUEUE  ];  then
    cast  --deps  `cat  $INSTALL_QUEUE`
    (  cast       `cat  $INSTALL_QUEUE` 1>/dev/null 2>&1  &&
         rm             $INSTALL_QUEUE
    )  &
  fi

  goodbye

}


foreground_execute() {

  [  -f         $REMOVE_QUEUE  ]  &&
  dispel  `cat  $REMOVE_QUEUE`
  rm  -f        $REMOVE_QUEUE

  [  -f         $INSTALL_QUEUE  ]  &&
  cast `cat  $INSTALL_QUEUE`
  rm  -f        $INSTALL_QUEUE

  goodbye

}


main_menu()  {

  S_HELP="Easy spell management."
  O_HELP="Change sorcery options and features."
  L_HELP="View and edit sorcery generated log files."
  Q_HELP="View and edit sorcery queues."
  F_HELP="Process queues while you watch and wait."
  B_HELP="Process queues in the background."
  E_HELP="Exit without processing queues."
  I_HELP="Setting your install/state/track root locations"
  C_HELP="Administrate groups of Unix/Linux boxes."
      OK="Select"
  CANCEL="Exit"
  while
    if  [  "$CABAL"  ==  "on"  ] ;  then 
        COMMAND=`eval $DIALOG ' --title "Main Menu"             \
                       --item-help                              \
                       --ok-label      "$OK"                    \
                       --cancel-label  "$CANCEL"                \
                       --menu                                   \
                       "Sorcery Version  $SORCERY_VERSION"      \
                       0 0 0                                    \
                       "S"  "Spell        Menu"     "$S_HELP"     \
                       "O"  "Option       Menu"     "$O_HELP"     \
                       "L"  "Log          Menu"     "$L_HELP"     \
                       "Q"  "Queue        Menu"     "$Q_HELP"     \
                       "F"  "Foreground   Execute"  "$F_HELP"     \
                       "B"  "Background   Execute"  "$B_HELP"     \
                       "I"  "Install Root Menu"   "$I_HELP"     \
                       "C"  "Cabal        Menu"     "$C_HELP"'`

    else
      COMMAND=`eval $DIALOG ' --title "Main Menu"               \
                       --item-help                              \
                       --ok-label      "$OK"                    \
                       --cancel-label  "$CANCEL"                \
                       --menu                                   \
                       "Sorcery Version  $SORCERY_VERSION"      \
                       0 0 0                                    \
                       "S"  "Spell        Menu"     "$S_HELP"     \
                       "O"  "Option       Menu"     "$O_HELP"     \
                       "L"  "Log          Menu"     "$L_HELP"     \
                       "Q"  "Queue        Menu"     "$Q_HELP"     \
                       "F"  "Foreground   Execute"  "$F_HELP"     \
                       "B"  "Background   Execute"  "$B_HELP"     \
                       "I"  "Install Root Menu"   "$I_HELP"'`
    fi
  do

    case  $COMMAND in
      S)  spell_menu          ;;
      O)  option_menu         ;;
      L)  log_menu            ;;
      Q)  queue_menu          ;;
      F)  foreground_execute  ;;
      B)  background_execute  ;;
      C)  cabal_menu          ;;
      I)  install_root_menu   ;;
    esac

  done

}



#---------------------------------------------------------------------
#-item sorcery_hold_spells <spells>
##
## sets <spells>'s status to held
##
## cli function
#---------------------------------------------------------------------
sorcery_hold_spells () {
    set_held $@
}


#---------------------------------------------------------------------
#-item sorcery_unhold_spells <spells>
##
## unholds <spells>'s status. (Sets it to installed)
##
## cli function
#---------------------------------------------------------------------
sorcery_unhold_spells () {
    set_unheld $@
}


#---------------------------------------------------------------------
#-item sorcery_set_default <spells>
##
## Used for setting default_depends/providers
##
## cli function
#---------------------------------------------------------------------
sorcery_cli_defaults () {
  local cmd=$1
  shift
  case $cmd in
    add) sorcery_add_defaults "$@" ;;
    search) sorcery_search_defaults "$@" ;;
    search) search_default_providers "$@" ;;
    remove) sorcery_remove_defaults "$@" ;;
    *) help ;;
  esac
}

#---------------------------------------------------------------------
#-item sorcery_add_default <spells>
##
## Used for setting default_depends/providers
##
## cli function
#---------------------------------------------------------------------
sorcery_add_defaults () {
    if [ $# -ne 3 ] ; then
      message "${PROBLEM_COLOR}Wrong number of arguments.${DEFAULT_COLOR}"
      help
    fi


    # check for this first as a slight optimization
    if [[ $3 != on ]] && [[ $3 != off ]] ; then
      message "${PROBLEM_COLOR}Please choose on or off.${DEFAULT_COLOR}"
      help
    fi

    if [[ ! $1 ]] && [[ ! $2 ]] ; then
      message "${PROBLEM_COLOR}Can't set anything to be the default" \
              "for everything!${DEFAULT_COLOR}"
    fi

    if [[ $1 ]] && ! codex_does_spell_exist $1; then
      #echo "$1 is not a spell" # already printed by codex_does_spell_exist
      help
    fi

    if [[ ! $2 ]] || codex_does_spell_exist $2 &>/dev/null; then
      add_default_depends $DEFAULT_DEPENDS "$@"
    elif codex_does_service_exist $2 ; then
      add_default_provider $DEFAULT_PROVIDERS "$@"
    else
      message "${SPELL_COLOR}$2${PROBLEM_COLOR} is not a valid choice." \
              "Please choose a spell, provider, or \"\".${DEFAULT_COLOR}"
      help
    fi || echo "Unknown error occured, contact the sorcery team"
}

#---------------------------------------------------------------------
#-item sorcery_search_default <spells>
##
## Used for searching default_depends/providers
##
## cli function
#---------------------------------------------------------------------
sorcery_search_defaults () {
  # it wont hurt to look in both
  search_default_depends $DEFAULT_DEPENDS "$@"
  search_default_provider $DEFAULT_PROVIDERS "$@"
}

#---------------------------------------------------------------------
#-item sorcery_remove_default <spells>
##
## Used for removing default_depends/providers
##
## cli function
#---------------------------------------------------------------------
sorcery_remove_defaults () {
  remove_default_depends $DEFAULT_DEPENDS "$@"
  remove_default_provider $DEFAULT_PROVIDERS "$@"
}

main() {

  rm  -f  $UPDATE_SCRIPT

  if [ -z $1 ]; then
    main_menu
  else
    case  $1  in
            -u|update)  update_sorcery                          ;;
     -s|system-update)  update_pkgs  autoupdate                 ;;
           -g|upgrade)  update_pkgs  upgrade                    ;;
             -q|queue)  update_queue                            ;;
         review-queue)  install_queue_history                   ;;
           -r|rebuild)  rebuild                                 ;;
                 hold) shift; sorcery_hold_spells   "$@"        ;;
               unhold) shift; sorcery_unhold_spells "$@"        ;;
              default*) shift; sorcery_cli_defaults "$@"        ;;


            -h|--help)  help                                    ;;
         -v|--version)  echo $SORCERY_VERSION                   ;;
                    *)  help                                    ;;
    esac
  fi

}


if  [  "$UID"  ==  0  ];  then
  . /etc/sorcery/config
  DIALOG='$DIALOGPROG  --backtitle "Sorcery Spell Management Utility" --stdout'

  SORCERY_VERSION=`cat /etc/sorcery/version`
  SORCERY_DIR=`codex_find_spell_by_name  sorcery-$SORCERY_BRANCH`
  #SORCERY_DETAILS="$SORCERY_DIR/DETAILS"
  main  "$@"
else
  if [[ $1 == -h ]] || [[ $1 == --help ]]; then 
    help
  else
    if [[ $1 == -v ]] || [[ $1 == --version ]]; then
      echo  $( cat /etc/sorcery/version )
    else
      echo  "Enter the root password, please."
      su  - -c  "DISPLAY=$DISPLAY PATH=$PATH  $0  $*"
    fi
  fi
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
##
#---------------------------------------------------------------------
