. $GRIMOIRE/libaccount
. $GRIMOIRE/libgcc

QT4DIR=$INSTALL_ROOT/opt/qt4
QT5DIR=$INSTALL_ROOT/opt/qt5

#---------------------------------------------------------------------
## Apply patches from a directory
#---------------------------------------------------------------------
function apply_patch_dir() {
  [ -d "$SPELL_DIRECTORY/$1" ] || return 0
  find "$SPELL_DIRECTORY/$1" \( -name \*.patch -o -name \*.diff \) -print0 |
  sort -zV | xargs -0 -n 1 -t patch -fp1 -i
}

#---------------------------------------------------------------------
## Replaces sorcerys default_pre_build with a custom version using
## the invoke_gcc function from libgcc
#---------------------------------------------------------------------
function default_pre_build () {
  invoke_gcc  &&
  real_default_pre_build
}

#---------------------------------------------------------------------
# Runs update-desktop-database if it is installed
#---------------------------------------------------------------------
function update_desktop_database ()
{
  if test -x /usr/bin/update-desktop-database; then
    message "${MESSAGE_COLOR}Updating application mime type database.${DEFAULT_COLOR}"
    /usr/bin/update-desktop-database
  fi
}

#---------------------------------------------------------------------
## Sets the current script to run only one make job
#---------------------------------------------------------------------

function make_single ()
{
  JOBS_PER_HOST=0  &&
     MAKE_NJOBS=1
}

#---------------------------------------------------------------------
## Re-enables the normal Sorcery make (cancels single_make)
#---------------------------------------------------------------------

function make_normal ()
{
  source $COMPILE_CONFIG
}

#---------------------------------------------------------------------
## replacement for config_query_string to work around a short timeout
## when entering long strings (hostnames, organisation names)
#---------------------------------------------------------------------
function config_query_long_string() {
    local ANSWER
    local DELAY=5 
    if config_get_option "$1" ANSWER; then
        # option allready answered in config
        echo -e "[[ ${QUERY_COLOR}$2${DEFAULT} -> '${QUERY_COLOR}$ANSWER${DEFAULT}' ]]"
    else
        query_string ANSWER "$2" "$3"
        read -t $DELAY -n 1 ANSWER_first
        if [[ $ANSWER_first ]] ; then 
          read ANSWER_rest
        fi
        ANSWER="${ANSWER_first}${ANSWER_rest}"
        config_set_option "$1" "$ANSWER"
    fi
    return 0
}

#---
## @Synopsis default_games_build function to replace
## @Synopsis all the duplication of the same stuff in games-grimoire
#---

function default_games_build() {
  OPTS="$OPTS --bindir=${INSTALL_ROOT}/usr/games \
  --datadir=${INSTALL_ROOT}/usr/share/games \
  --localstatedir=${INSTALL_ROOT}/var/games"  &&
  default_build
}

# cmake flags use : which is an internal sorcery delimiter.
# In order to facilitate the passing of depends flags, use % instead and call
# this function at the start of BUILD. Don't use it anywhere else.
# Example:
# DEPENDS: depends kdelibs4 -DCRUFT%BOOL=FALSE; ...
# BUILD: prepare_cmake_flags; ...
function prepare_cmake_flags()
{
  OPTS="${OPTS//%/:}"
}

#---
## @Synopsis cmake_build function to build
## @Synopsis source code with cmake
#---

cmake_build() {
  mkdir -p build        &&
  cd build              &&
  prepare_cmake_flags   &&

  if [[ -z $1 ]];then
    CMAKE_INSTALL_PREFIX="$INSTALL_ROOT/usr"
  else
    CMAKE_INSTALL_PREFIX="$1"
  fi &&

  message INSTALL_PREFIX=$CMAKE_INSTALL_PREFIX &&

  if is_depends_enabled $SPELL qt6base;then
    OPTS+=" -DCMAKE_PREFIX_PATH=$QT6DIR/lib/cmake"
  fi &&

  cmake -DCMAKE_INSTALL_PREFIX=$CMAKE_INSTALL_PREFIX \
        -DCMAKE_INSTALL_BINDIR=games \
        -DCMAKE_INSTALL_LIBDIR=lib \
        -DCMAKE_INSTALL_DATAROOTDIR=share/games \
        -DCMAKE_INSTALL_SYSCONFDIR=$INSTALL_ROOT/etc \
        -DCMAKE_BUILD_TYPE=$CM_BUILD_TYPE \
        -DCMAKE_C_FLAGS_RELEASE="$CFLAGS" \
        -DCMAKE_CXX_FLAGS_RELEASE="$CXXFLAGS" \
         $OPTS ../  &&
  cmake --build .
}

function cmake_install() {
  cmake --install .
}

#---
## @Synopsis qt4_cmake_build function to build
## @Synopsis source code with QT4 and cmake
#---
#
qt4_cmake_build() {
  PATH="$QT4DIR/bin/:$PATH"
  export PKG_CONFIG_PATH="$QT4DIR/lib/pkgconfig"
  cmake_build ${1-$QT4DIR}
}

#---
## @Synopsis profile_install function to make installing
## @Synopsis of /etc/profile.d/$spell.sh easier...
#---

function profile_install() {
  if [ -f ${SCRIPT_DIRECTORY}/profile/${SPELL}.sh ] ; then
    if ! [ -e ${INSTALL_ROOT}/etc/profile.d/${SPELL}.sh ] ; then
      install  -m  755  ${SCRIPT_DIRECTORY}/profile/${SPELL}.sh \
                        ${INSTALL_ROOT}/etc/profile.d/${SPELL}.sh
    fi
  fi
   
}


#-------------------------------------------------------------------------
## Compatibility code for gracefully failing if the user uses an older
## version of sorcery with a spell that calls unpack_file.
#-------------------------------------------------------------------------
declare -f unpack_file &> /dev/null ||
function unpack_file() {
  message "This spell uses a function only available in sorcery 1.12.2 or newer, please update."
  return 1
}

#---
## @Synopsis A function to find all dirs and files and set them to
## @Synopsis proper permissions.
#---

function find_and_scam() {
  find ./ -type d -print0 | xargs -r -0 -n 1 chmod 0750
  find ./ -type d -print0 | xargs -r -0 -n 1 chown root:games
  find ./ -type f -print0 | xargs -r -0 -n 1 chmod 0640
  find ./ -type f -print0 | xargs -r -0 -n 1 chown root:games
}

#---
## @Synopsis games_create_base_dirs function to replace
## @Synopsis all the duplication of the same stuff in games-grimoire
## @Synopsis and to provide some basics for all spells
#---

function games_create_base_dirs() {
  mkdir -vp ${INSTALL_ROOT}/usr/share/games/${SPELL}
  mkdir -vp ${INSTALL_ROOT}/usr/games
  mkdir -vp ${INSTALL_ROOT}/var/games
}

#---
## @Synopsis games_make_proper_binary function to make all
## @Synopsis binaries in /usr/games chown root.games and
## @Synopsis chmod 0750.
#---

function games_make_proper_binary() {
if grep -q "usr/games/" $IW_LOG > /dev/null 2>&1
then
  grimoire_parse_iw $IW_LOG | grimoire_exists | sort | grep "usr/games/" | xargs -r -n 1 chmod -f 0750
  grimoire_parse_iw $IW_LOG | grimoire_exists | sort | grep "usr/games/" | xargs -r -n 1 chown -f root:games
elif [[ $STAGED_INSTALL == on ]]
then
  echo "doing the stage root thing"
  find $STAGE_DIRECTORY/TRANSL/ | sed "s#$STAGE_DIRECTORY/##" | grep '^TRANSL/usr/games' | xargs -r -n 1 chmod -f 0750
  find $STAGE_DIRECTORY/TRANSL/ | sed "s#$STAGE_DIRECTORY/##" | grep '^TRANSL/usr/games' | xargs -r -n 1 chown -f root:games
else
message "${QUERY_COLOR}If you see this message and you're not \n \
installing a data spell then report this at the following url: \n \
http://bugs.sourcemage.org/enter_bug.cgi?product=Codex&bug_status=NEW&version=games%20grimoire&component=games%20grimoire&rep_platform=Other&op_sys=other&priority=P2&bug_severity=minor&assigned_to=games%40sourcemage.org&cc=&bug_file_loc=http%3A%2F%2F&short_desc=${SPELL}%20not%20installing%20binaries%20properly&comment=&dependson=&blocked=9312&maketemplate=Remember%20values%20as%20bookmarkable%20template&form_name=enter_bug \
${DEFAULT_COLOR}"
fi
}

#---
## @Synopsis default_post_install function to
## @Synopsis clean out any empty share/games/SPELL dirs
## @Synopsis clean out any empty gather docs dirs
## @Synopsis and run the real_default_post_install afterwards
#---

function default_post_install() {
  games_make_proper_binary &&
  if [[ $STAGED_INSTALL == on ]]; then
    rmdir --ignore-fail-on-non-empty ${STAGE_DIRECTORY}/TRANSL/usr/share/games/${SPELL} &&
    rmdir --ignore-fail-on-non-empty ${STAGE_DIRECTORY}/TRANSL/usr/share/games          &&
    rmdir --ignore-fail-on-non-empty ${STAGE_DIRECTORY}/TRANSL/usr/share/doc/${SPELL}   &&
    rmdir --ignore-fail-on-non-empty ${STAGE_DIRECTORY}/TRANSL/usr/share/doc            &&
    rmdir --ignore-fail-on-non-empty ${STAGE_DIRECTORY}/TRANSL/usr/share
  else
    rmdir --ignore-fail-on-non-empty ${INSTALL_ROOT}/usr/share/games/${SPELL} &&
    rmdir --ignore-fail-on-non-empty ${INSTALL_ROOT}/usr/share/games          &&
    rmdir --ignore-fail-on-non-empty ${INSTALL_ROOT}/usr/share/doc/${SPELL}   &&
    rmdir --ignore-fail-on-non-empty ${INSTALL_ROOT}/usr/share/doc            &&
    rmdir --ignore-fail-on-non-empty ${INSTALL_ROOT}/usr/share
  fi
  real_default_post_install
}

#---
## @Synopsis default_pre_install function to
## @Synopsis create some base dirs for spells
## @Synopsis after running real_default_pre_install
#---

function default_pre_install() {
  create_group games &&
  real_default_pre_install &&
  games_create_base_dirs
}

#---
## @Synopsis a parse_iw clone function
#---

function grimoire_parse_iw()  {
  local INPUT=$1
  
  # it is EXTREMELY IMPORTANT that this variable contains an actual
  # tab character and not some number of spaces. Otherwise BAD THINGS
  # will happen.
  local TAB=$'\t'
  OMIT_IN="${TAB}rename\|${TAB}symlink\|${TAB}unlink"
  
  grep -v "$OMIT_IN" $INPUT | cut -f3 | grep "^/"
  cat                $INPUT | cut -f4 | grep "^/"
}

#---
## @Synopsis an exists clone function
#---
function grimoire_exists()  {
  while  read  ITEM;  do  [  -e  "$ITEM"  ]  &&  echo  "$ITEM";  done;
}

#---
## @Synopsis verify_file function until it's in stable sorcery
#---
declare -f verify_file &>/dev/null ||
function verify_file() {
  local SVAR="SOURCE${FILENUM}"
  local AVAR="SOURCE${FILENUM}_HASH"
  unpack_hash ${!SVAR} ${!AVAR}
}


#---
## disable_no_plt
## A function for disabling -fno-plt
#---
disable_no_plt() {
    CFLAGS=${CFLAGS//-fno-plt}     &&
    CXXFLAGS=${CXXFLAGS//-fno-plt}
}

#---
## disable_pic
## A function to smartly disable -DPIC and -fPIC flags
## has one optional parameter: force which forces disable
#---

disable_pic() {
  if [[ "${SMGL_COMPAT_ARCHS[1]}" != "x86_64" ]] &&
     [[ "${SMGL_COMPAT_ARCHS[1]}" != "em64t"  ]] &&
     [[ "${SMGL_COMPAT_ARCHS[1]}" != "alpha"  ]] ||
     [[ "$1" == "force" ]]
  then
    CFLAGS=${CFLAGS//-fPIC}                    &&
    CFLAGS=${CFLAGS//-DPIC}                    &&
    CXXFLAGS=${CXXFLAGS//-fPIC}                &&
    CXXFLAGS=${CXXFLAGS//-DPIC}                &&
    disable_no_plt
  fi
}

#
## Function to check if we're using xorg-modular libs or not
#
function check_if_xorg_modular_libs()
{
  if  [[  "$(get_spell_provider  ${1:-$SPELL}  X11-LIBS)"  ==  "xorg-server"  ]] ||
      [[  "$(get_spell_provider  ${1:-$SPELL}  X11-LIBS)"  ==  "xorg-libs"  ]]     
  then
     return 0
  fi
  return 1
}

#
## Function to check if we're using xorg-modular server or not
#

function check_if_xorg_modular_server()
{
   if  [[  "$(get_spell_provider  ${1:-$SPELL}  X11-SERVER)"  ==  "xorg-server"  ]]
   then
      return 0
   fi
   return 1
}

#-------------------------------------------------------------------------
## Default build for Python spell.
#-------------------------------------------------------------------------
function default_build_python() {
  python setup.py build "$@"
}

#-------------------------------------------------------------------------
## Default install for Python spell.
#-------------------------------------------------------------------------
function default_install_python() {
  python setup.py install --root "$INSTALL_ROOT/" "$@"
}

#---
## Select SCM branch. If no parameter is given, it assumes a single scm branch.
##
## Saves selected branch in ${SPELL}_BRANCH, and auto-update setting on
## ${SPELL}_AUTOUPDATE.
##
## Usage:
##   . ${GRIMOIRE}/FUNCTIONS &&
##   prepare_select_branch [branch] ...
#---
function prepare_select_branch() {
  local spell=$(get_up_spell_name) &&
  local branch="$spell"_BRANCH &&

  if [[ $# > 1 ]]; then
    config_query_list $branch "Select one of the available branches:" "$@"
  else
    eval $branch=\""${1:-scm}"\"
  fi &&

  if [[ "${!branch/-*}" = scm ]]; then
    config_query "$spell"_AUTOUPDATE 'Automatically update on every system update?' n
  fi
}

#---
## Get uppercase spell name with _ instead of -
#---
function get_up_spell_name() {
  echo ${1:-$SPELL} | tr "a-z-" "A-Z_"
}

#---
## Get branch-based/autoupdate-aware version number
#---
function get_scm_version() {
  local spell=$(get_up_spell_name) &&
  local spell_branch="${spell}_BRANCH" &&
  local spell_autoupdate="${spell}_AUTOUPDATE" &&
  if [ "${!spell_autoupdate}" = "y" ]; then
      echo $(date "+%Y%m%d")
  else
      echo ${!spell_branch:-scm}
  fi
}

function qt5_cmake_build() {
  PATH="$QT5DIR/bin/:$PATH"
  export PKG_CONFIG_PATH="$QT5DIR/lib/pkgconfig"
  cmake_build ${1-$QT5DIR}
}

. $GRIMOIRE/glselect.function
