#---
## @Synopsis Sets up some global variables that contain sources and urls
## @Synopsis delimited by newlines
#---
function get_sources_and_urls()
{
  sources_and_urls=$(eval ${if_var:-:}; . DETAILS &> /dev/null; get_spell_files_and_urls)
  sources=$(cut -d" " -f1 <<< "$sources_and_urls")
  source_urls=$(cut -d" " -f2 <<< "$sources_and_urls")
}

#---
## @Synopsis Sets a variable from details, first setting the flag if_var
## @param variable to set
#---
function conditional_set_var()
{
  eval ${if_var:-:}; . DETAILS &> /dev/null; eval echo -n \$$1
}

#---
## @Synopsis Increments or removes PATCHLEVEL or SECURITY_PATCH. Asks first
## @Synopsis unless the second argument is "skip". Adds variable if necessary.
##
## @param PATCHLEVEL or SECURITY_PATCH - work with which wone?
## @param (optional) skip the query? skip to skip
## @param (optional) remove, increment, add? remove to remove
## @param (optional) default answer for the query, default is n
#---
function update_patchlevel()
{
  local current_value=$(conditional_set_var $1)

  if [[ -z $current_value ]]
  then
    [[ $3 == remove ]] && return
    if [[ $2 == skip ]] || query "Do you want to add $1?" ${4:-n}
    then
      update_patchlevel_sub $1 none add
    fi
  else
    if [[ $2 == skip ]] || query "Do you want to increment $1?" ${4:-n}
    then
      update_patchlevel_sub $1 $current_value $3
    fi
  fi
}

function update_patchlevel_sub()
{
  local current_value=$2 action=$3 new_value count

  if [[ $current_value == none ]]
  then
    new_value=$(count_spaces $1)
    sed -i "s, VERSION=['\"]*${SPELL_VERSION}['\"]*\s*$,&\n$new_value$1=1," DETAILS
    add_history_entry "DETAILS: $1++"
  else
    new_value=$(( current_value + 1 ))
    count=$(grep -c "^[^#]*$1=['\"]*${current_value}['\"]* *$" DETAILS)
    if (( $count  > 1 ))
    then
      echo
      message "Two or more $1 variables with the same value found."
      error_msg "All will be changed - revert the bad ones manually."
      echo
    fi
    if [[ $action == remove ]]
    then #PATCHLEVEL removal on version updates
      sed -i "/^[^#]*$1=['\"]*${current_value}['\"]*/d" DETAILS
    else
      sed -i "/^[^#]*$1=['\"]*${current_value}['\"]*/ s,=.*$,=$new_value," DETAILS
      add_history_entry "DETAILS: $1++"
    fi
  fi
}

#---
## @Synopsis Compute how to insert $1, so = will be aligned properly
## @Synopsis it finds the most used = position
##
## @return string with adequate number of spaces
#---
function count_spaces()
{
  local count spaces eq_col
  eq_col=$(awk -F '=' '{ if($1)print length($1) }' DETAILS | sort | uniq -c | sort -n | sed -n '$ s,^\s*\S*\s,,p')
  count=$(( $eq_col - ${#1} ))
  for (( i=0 ; i<$count; i++ )) ; do
    spaces="$spaces "
  done
  echo "$spaces"
}

#---
## @Synopsis Finds the spell under $QUILL_GIT_DIR
#---
function copy_git_sub()
{
  if [[ -z $QUILL_GIT_DIR ]]
  then
    error_msg "\$QUILL_GIT_DIR is empty, run quill -r to set it!"
    echo
    return 1
  fi

  # find where under $QUILL_GIT_DIR the spell actually is
  # perhaps the section path is /home/navaden/sorcery/git/gnome1-libs
  # + is the only regex char that is problematic here AND is used in names
  SECTION2=$(find "$QUILL_GIT_DIR" -regex "${QUILL_GIT_DIR%/}/[^.][^/]*/[^/]*/${SPELL_NAME//+/\+}$" -type d -printf "%h\n" -quit)
  if [[ -z $SECTION2 ]]
  then
    error_msg "Couldn't find the spell, \$QUILL_GIT_DIR is probably bad!"
    echo
    return 1
  fi
  GRIMOIRE2="${SECTION2%/*}" # full path
  # we need just the name
  SECTION2="${SECTION2##*/}"
}

#---
## @Synopsis Copies the spell to $QUILL_GIT_DIR
#---
function copy_to_git()
{
  copy_git_sub || return 1

  if [[ ! -e $QUILL_SPELL_DIR/$SPELL_NAME ]]
  then
    error_msg "There is nothing to copy back!"
    return 1
  fi

  quill_final_put_in_grimoire "$GRIMOIRE2" "$SECTION2" no
  unset GRIMOIRE2 SECTION2
}

#---
## @Synopsis Copies the spell from $QUILL_GIT_DIR to $QUILL_SPELL_DIR
#---
function copy_from_git()
{
  copy_git_sub || return 1

  # we wipe it first, so we can handle any files that were deleted
  cd $QUILL_SPELL_DIR
  rm -rf "$QUILL_SPELL_DIR/$SPELL_NAME"

  if [[ -w $QUILL_SPELL_DIR ]]
  then
    cp -pr "$GRIMOIRE2/$SECTION2/$SPELL_NAME" "$QUILL_SPELL_DIR"
  else
    ${QUILL_SUDO:-su} -c "cp -pr '$GRIMOIRE2/$SECTION2/$SPELL_NAME' '$QUILL_SPELL_DIR'"
  fi

  # update SPELL_UPDATED
  codex_get_spell_paths $(codex_find_spell_by_name $SPELL_NAME)
  diff -q $QUILL_SPELL_DIR/$SPELL_NAME "$GRIMOIRE/$SECTION/$SPELL_NAME" -x DETAILS.orig > /dev/null || SPELL_UPDATED=y

  unset GRIMOIRE2 SECTION2
  cd $QUILL_SPELL_DIR/$SPELL_NAME
}

#---
## @Synopsis Removes unneeded sigs
##
## @param old version
#---
function remove_old_sigs()
{
  local version="$1"
  if ! grep -q "VERSION=$version *$" DETAILS;
  then
    # compgen has a plain wierd output
    # lynx wants interactivity and no 404s
    # the glob could expand to more than one file, so test -e could break
    files=$(compgen -G "*$version*.sig" | tr '\n' ' ')
    files="$files $(compgen -G "*$version*.asc" | tr '\n' ' ')"
    [[ $files != " " ]] && rm -i $files
  fi

}

#---
## @Synopsis Unexpands SOURCE_GPG if necessary to be later able to match it
##
## @return 0 if current_check was found
## @return 1 otherwise
#---
function unexpand_source_gpg()
{
  local j

  if grep -q "$current_check" DETAILS.orig
  then
    return 0
  else # looks like it is expanded
    current_check=$(
    eval ${if_var:-:}; . DETAILS.orig &> /dev/null;
    for j in `get_source_nums s`
    do
      j="${j%s}"
      SOURCE=$(eval echo \$SOURCE$j)
      substitute_with_variables current_check "$SOURCE" {SOURCE$j}
    done
    substitute_with_variables current_check "$SPELL_NAME" {SPELL} "$VERSION" {VERSION}
    echo $current_check
    )
  fi
  if grep -q "$current_check" DETAILS.orig
  then # maybe the author doesn't like the ugly braces too
    return 0
  else
    current_check="$(tr -d "{}" <<< "$current_check")"
  fi
  if grep -q "$current_check" DETAILS.orig
  then
    return 0
  else # give up
    error_msg "Giving up, you'll have to update SOURCE${i}_(GPG|HASH) yourself."
    return 1
  fi
}

#---
## @Synopsis Ask to copy the spell to our working dir - QUILL_SPELL_DIR
## @Synopsis If QUILL_SPELL_DIR is empty, just do it
## @Synopsis It also moves there and does the DETAILS.orig copy
##
## @return 0 if everything is ok
## @return 1 otherwise
#---
function ask_and_copy_over()
{
  local reply noop_answer="No" # noop_answer needs to be only one word!

  [[ ! -d $QUILL_SPELL_DIR/$SPELL_NAME ]] && unset noop_answer

  #copy spell over and move there
  query_list "Do you want to copy the spell from someplace?" reply "The grimoire" "The grimoire" "QUILL_GIT_DIR" $noop_answer

  [[ $reply == $noop_answer ]] && return 0
  if [[ $reply == "The grimoire" ]]
  then
    codex_get_spell_paths $(codex_find_spell_by_name $SPELL_NAME) &&
    cd $QUILL_SPELL_DIR &&
    rm -fr $QUILL_SPELL_DIR/$SPELL_NAME &&
    cp -pr $SECTION_DIRECTORY/$SPELL_NAME $QUILL_SPELL_DIR &&
    message "Done." &&
    SPELL_UPDATED=n
  elif [[ $reply == "QUILL_GIT_DIR" ]]
  then
    copy_from_git &&
    message "Done."
  else
    error_msg "Bad choice"
    ask_and_copy_over
    return
  fi &&
  cd $QUILL_SPELL_DIR/$SPELL_NAME &&
  cp DETAILS DETAILS.orig || return 1
}


#---
## @Synopsis Checks if the spell is multiversioned and sets the delimiter
## @Synopsis variable (if_var) if it is
#---
function multiversion_check()
{
  if [[ ${#versions[@]} != 1 ]]
  then #we have a problem
    message "Oh dear, detected a multiversion spell. Going to cat DETAILS for you "
    message "and then you will tell me which variable I need to set, so I can get "
    message "to the correct version ($version)."
    sleep 3
    cat DETAILS
    query_string if_var "${QUERY_COLOR}Please enter the appropriate variable. Example: UGU_DEVEL=y${DEFAULT_COLOR} "
  fi
}

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