#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-05-05; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.live.builder.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.live.builder
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing || return "${ERR_GUARD_SRCE}"

#######################################
# Debugger module for xtrace to debug log.
# Globals:
#   BASH_XTRACEFD
#   LOG_DEBUG
#   LOG_VAR
#   PS4
#   SHELLOPTS
#   VAR_DUMP_VARS_INITIAL
#   VAR_EARLY_DEBUG
#   VAR_ISO8601
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
debugger() {
  ### Capture an initial snapshot of all variables (excluding '^(BASH|_).*')
  # shellcheck disable=SC2155
  declare -grx VAR_DUMP_VARS_INITIAL=$(mktemp)

  # shellcheck disable=SC2312
  {
    declare var
    while IFS= read -r var; do
      declare -p "${var}" 2>/dev/null
    done < <(compgen -v | grep -Ev '^(BASH|_).*')
  } | sort >| "${VAR_DUMP_VARS_INITIAL}"

  declare -gx VAR_EARLY_DEBUG="true"
  ### Set a verbose PS4 prompt including timestamp, source, line, exit status, and function name

  declare -grx PS4='\e[97m+\e[96m[${EPOCHREALTIME}]\e[97m:\e[94m[$$]\e[97m:\e[92m[${BASH_SOURCE[0]}:${LINENO}]\e[97m:\e[93m[${?}]\e[97m:\e[95m[${FUNCNAME[0]:-main}()]\e[97m>>\e[0m '
  declare -grx LOG_DEBUG="/tmp/cdlb_${VAR_ISO8601}_debug.log"
  declare -grx LOG_VAR="/tmp/cdlb_${VAR_ISO8601}_var.log"

  ### Generates empty LOG_DEBUG and LOG_VAR
  touch "${LOG_DEBUG}" && chmod 0600 "${LOG_DEBUG}"
  touch "${LOG_VAR}"   && chmod 0600 "${LOG_VAR}"

  ### Open file descriptor 42 for writing to the debug log
  exec 42>| "${LOG_DEBUG}"

  ### Write Debug Log Header https://www.gnu.org/software/bash/manual/html_node/Bash-Variables
  debug_header "$#" "$*"

  ### Tell Bash to send xtrace output to FD 42
  export BASH_XTRACEFD=42

  ### Enable inheritable shell options
  export SHELLOPTS

  ### Turn on xtrace
  set -x

  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f debugger
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
