#!/bin/bash

LOCK_DIR=/tmp/lock-dir

# 10 so it gets sources first, fwiw
#this file contains all the functions that might be needed by other
# modules
#common functions

# wrapper for dialog, should eventually replace the ugly ${DIALOG[*]}
function run_dialog() {
  debug_sleep "pre-dialog"
  debug_log "dialog" 3 "run_dialog called with the following arguments:" "$@"

  dialog --backtitle "Source Mage GNU/Linux Installer v. ${INSTALLER_VERSION}" \
         --stdout --cr-wrap "$@"

  local rc=$?
  [[ $rc == 255 ]] && debug_log "ERROR" -1 "run_dialog failed, params:" "$@"
  return $rc
}

# explode(): split up a string into an array at a given delimiter
# (stolen from sorcery's libmisc)
# $1: string to explode
# $2: string to cut at
# $3: name of the array to put the result into
#
# Note: The array you want the fields put into must be
# declared before you call this function.
# EXAMPLE
#
# my_array=()
# explode "a_string_to_explode" "_" "my_array"
# echo my_array[*]
#
# Produces "a" "string" "to" "explode".
#
# also comes in handy as
# explode "$(list_parts)" $'\n' "LIST_PARTS"
#---------------------------------------------------------------------
function explode()
{ # $1==string to explode, $2==delimiter, $3==name of array to put it in

  [[ "$3" ]] || return 1
  local l=$1
  local i=0
  while [[ $l ]]; do
    local result=${l%%$2*}
    l=${l#"$result"}
    l=${l#$2}
    eval "$3[$i]=\"$result\""
    let i++
  done
  # this adds an empty array element at the end if the line ended in $2
  local lc=${1//\*$2/true}
  if [ "$lc" = "true" ]; then
    eval "$3[$i]=\"\""
  fi
}

#inputbox: creates a simple input box based off the two passed parameters
function inputbox()  {

  run_dialog  --nocancel --inputbox "$1" \
    0 0 "$2"

}

#chroot_cmd: Creates a chrooted environment
# usage: chroot_cmd cmd args...
function chroot_cmd() {

  debug_log "chroot_cmd" 3 "chroot_cmd called with the following arguments:" "$@"

  chroot "${TARGET}" "$@"

}

#confirm: displays a confirm dialog
#basically "do you want to ... <yes> <no>"
#$1 is the question, the other args can be options to dialog
# SECTION: MISC
function confirm()  {

    local query="$1"
    shift
    run_dialog "$@" --yesno  "$query" 0 0

}

# Displays a dialog menu for the given entries, and remembers the last answer.
# When the same menu is ran again, it re-uses the answer as default.
# Args:
# $1: internal identifier (for remembering)
# $2: menu title
# $3: additional options (e.g. --item-help) - no quoting possible
# $4: menu text
# $5: initial default selection
# $*: menu items
function memory_menu() {
  local ID="$1"
  local TITLE="$2"
  local OPTS="$3"
  local TEXT="$4"
  local DEF="$5"
  shift 5
  local USEDEF="$(get_dependency "remember_$ID" 2>/dev/null)"
  USEDEF="${USEDEF:-"$DEF"}"
  local ANSWER
  ANSWER=$(run_dialog --title "$TITLE" $OPTS \
                 --default-item "$USEDEF"    \
                 --menu "$TEXT" 0 0 0        \
                 "$@")                       &&
  fill_dependency "remember_$ID" "$ANSWER"   &&
  echo "$ANSWER"
}

# displays a message
function display_message() {
  run_dialog --msgbox "$1" 0 0
}

#adding some functions for dependency management
# $1: Dependency to fill
# $2: [Optional] extra info to save
# should always return success
function fill_dependency() {
  mkdir -p $DEPENDS_DIR
  echo "${2:-fill}" >>${DEPENDS_DIR}/$1
}

# Returns the extra info saved with a dependency (only the latest)
# $1: Dependency to check
# stdout: the info
function get_dependency() {
  tail -n 1 ${DEPENDS_DIR}/$1
}

#looks through the depends file to see if your requested key exists
# $1: Dependency to check
# $2: [Optional] extra info to check for (regex)
# Returns 0 on found, 1 on not fulfilled, 2 on extra info not found
function check_dependency() {
  if [ -e ${DEPENDS_DIR}/$1 ] ;then
    if grep -q "$2" ${DEPENDS_DIR}/$1 ;then
      return 0; # if $2 is not given, "" matches anything
    else
      return 2;
    fi
  else
    return 1;
  fi
}


#ask the user if should continue, if yes, write the depends and note that it's
# at user's own risk
# otherwise fall out to the main menu?
# $1 is depends key
function need_dependency() {
  check_dependency $1 ||
  {
    confirm "The selected step needs $1 to be done first.
Do you want to continue anyway and skip $1?" --defaultno &&
    fill_dependency $1 force
  }
}

# Ask the user if he wants to do this yet,
# it's physically possible but rarely done in that order
function want_dependency() {
  check_dependency $1 ||
  confirm "Normally, $1 is done before this step. Continue anyway?"
}

# Blocks until specified stuff is fulfilled
function wait_depends() {
  while ! check_dependency "$@" ;do
    sleep 10
  done
}

# Lock specified resource
# waits until specified resource is not locked, then locks it
# $1: resource to lock
function lock_resource() {
  mkdir -p $LOCK_DIR
  while [ -e $LOCK_DIR/$1 ] ;do
    sleep 1
  done
  echo $$ >$LOCK_DIR/$1
}

# Unlock specified resource
# $1: resource to unlock
function unlock_resource() {
  rm -f $LOCK_DIR/$1
}

#dkowis discovered dialog's progress bar!
# Stdin is each element new line seperated
# $1 is the total amount
# $2 is the title
# $3 is the Initial text to display in the dialog
# $4 is the optional prefix "Doing $LINE..."
function progress_bar() {
    local COUNT=0
    local LINE
    local PCT
    while read LINE; do
        (( COUNT++ ))
        PCT=$(( $COUNT * 100 / ${1} ))
        if [ "${4}" != "" ]; then
            echo "XXX"
            echo "${4} $LINE..."
            echo "XXX"
        fi
        echo $PCT
    done | run_dialog --title "${2}" --gauge "${3}" 10 70 0
}
