#!/bin/bash
# Debug levels ought to be:
# 3: verbose debugging
# 2: debugging info
# 1: info about e.g. what gets installed
# 0: status of the installer itself
#-1: errors (use function "ERROR")

DEBUG_DIR=/tmp/debug_dir
function init_debug() {
  mkdir -p $DEBUG_DIR
  for DBG_file in $DATA_DIR/default_debug* ;do
    cp $DBG_file $DEBUG_DIR/${DBG_file##*/default_}
  done
}

# Main menu to configure debugging
function debug_screen() {
  local DBGCOMMAND
  DBGCOMMAND=$(run_dialog          \
    --title "Debugging menu"       \
    --item-help                    \
    --menu "Select the debugging level you want to change.
Higher numbers mean more debugging." \
    0 0 0                        \
    "A" "debug dialog parameters"  \
    "Log all parameters that dialog is called with" \
    "B" "debug chroot'ed commands" \
    "Log all parameters of all commands run inside the chroot" \
    "C" "show all command outputs" \
    "Make all programs, regardless of exit status, explicitly show output" \
    "D" "sleep before dialogs"     \
 "Sleep a bit before placing a dialog window, so you can read error messages" \
    "L" "lazy bg-installer"        \
    "spell installer waits for menu to need a spell before it does something" \
    "O" "other debugging"          \
    "Manually enter a component and debug level") &&
  case $DBGCOMMAND in
    A) echo 3 >$DEBUG_DIR/debug_dialog ;;
    B) echo 3 >$DEBUG_DIR/debug_chroot_cmd ;;
    C) echo 3 >$DEBUG_DIR/debug_tryrun ;;
    D) echo 2 >$DEBUG_DIR/debug_pre-dialog ;;
    L) touch $SI_QUEUE_DIR/debug ;;
    O) debug_menu_manual ;;
  esac
}

function debug_menu_manual() {
  local component=$(inputbox \
    "Enter the name of the component for which
you want to set the debug level" \
    "diskStructure")

  local level=$(cat $DEBUG_DIR/debug)
  [ -e $DEBUG_DIR/debug_$component ] &&
  level=$(cat $DEBUG_DIR/debug_$component)

  level=$(inputbox \
    "Please set the new debug level for $component" \
    $level) &&
  echo $level >$DEBUG_DIR/debug_$component
}

# Runs a command, captures its output, displays it nicely if it fails.
# If the command is a pipe, you'll need eval. Let's hope that won't happen.
# Possible parameters:
# -e "string": specify your own failure message
# -nc: (no-capture) don't redirect output
# -q: do not prompt user or print error, just log
function try_run() {
  local error_message
  local capture=true
  local quiet=false
  local capfile=$TMP_DIR/debug.out.$$
  local rc
  debug_log "tryrun" 3 "Argument list before parameter parsing:" "$@"
  while [[ "$1" == -* ]] ;do
    case "$1" in
       "-e") error_message="$2"
             shift 2
          ;;
      "-nc") capture=false
             echo "<not captured>" >$capfile
             shift
          ;;
       "-q") quiet=true
             shift
          ;;
          *) debug_log "ERROR" -1 "Unknown parameter to try_run: $1"
             shift
          ;;
    esac
  done
  debug_log "tryrun" 3 "Command to run:" "$@"
  error_message=${error_message:-"Running $1 failed."}
  if $capture ;then
    set -o pipefail
    "$@" 2>&1 | tee $capfile
    rc=$?
    set +o pipefail
    if [[ $rc != 0 ]] || debug_is_on "tryrun" 3 ;then
      $quiet ||
      run_dialog --title "$error_message" --cr-wrap --msgbox \
        "The failed command (exit code $rc) was:
$*
The (error) output was:
$(cat $capfile)" 0 0
    fi
  else
    "$@"
    rc=$?
    if [[ $rc != 0 ]] || debug_is_on "tryrun" 3 && ! $quiet ;then
      echo "$error_message"
      echo "The return code was $rc. The command was:"
      echo "$*"
      debug_enter "ERROR" -1
    fi >&2
  fi
  if [[ $rc != 0 ]] ;then
    debug_log "ERROR" -1 "$1 failed (rc=$rc)" "$@" "error:" "$(cat $capfile)"
  else
    debug_log "tryrun" 3 "$1 executed successfully, the full command was" \
              "$@" "Output was" "$(cat $capfile)"
  fi
  return $rc
}

# Params:
# $1: component
# $2: debug level
# Returns 1 when debugging is enabled
function debug_is_on() {
  local func=$1
  local priority=${2:-2} # Default to 2
  if [ -e $DEBUG_DIR/debug_$func ] ;then
    [ $(cat $DEBUG_DIR/debug_$func) -ge $priority ]
  else
    [ $(cat $DEBUG_DIR/debug) -ge $priority ]
  fi
}

# Sleeps for given time
# Usage:
# debug_sleep <component> time
function debug_sleep() {
  debug_is_on "$1" &&
  sleep ${2:-5}
  true
}

# display a single line and wait for the user to press enter
# $1: component, $2: debug level
function debug_enter() {
  debug_is_on "$1" $2 &&
  read -p "Press enter..."
  true
}

# Logs given text
# Usage:
# debug_log <component> <log at debug level> <string[s] to log>
# e.g. debug_log "diskStructure" 3 "Chosen device $DEV"
function debug_log() {
  local func=$1
  local priority=$2
  shift 2
  debug_is_on "$func" $priority || return 0
  lock_resource INSTALLER_DEBUG
  if [ $# == 1 ] ;then
    echo "$(date +%H:%M:%S) ${func}($$)@$priority: $*" >>${INSTALLER_DEBUG}
  elif [ $# -gt 1 ] ;then
    local var
    echo "$(date +%H:%M:%S) ${func}($$)@$priority: <several vars>" >>$INSTALLER_DEBUG
    for var in "$@" ;do
      echo "> $var" >>$INSTALLER_DEBUG
    done
  else
    echo "$(date +%H:%M:%S) ERROR($$)@-1: debug_log called incorrectly:" \
      "\"$func\" \"$priority\"" >>$INSTALLER_DEBUG
  fi
  unlock_resource INSTALLER_DEBUG
  true
}
