#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.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.installer
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing

#######################################
# Check for DEBUG mode.
# Arguments:
#  None
#######################################
pre_scan_debug() {
  # shellcheck disable=SC2155
  declare script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  . "${script_dir}/0100_arg_mismatch.sh"
  declare args=("$@")
  declare dbg_index=-1
  declare dbg_count=0
  declare i j

  for i in "${!args[@]}"; do
    if [[ "${args[i]}" == "-d" || "${args[i]}" == "--debug" ]]; then
      dbg_index=$i
      . "${script_dir}/0051_debug_var_dump.sh"
      declare -grx LOG_VAR="/tmp/ciss_debian_installer_$$_var.log"
      touch "${LOG_VAR}" && chmod 0600 "${LOG_VAR}"
      dump_vars_initial
      break
    fi
  done

  if (( dbg_index >= 0 )); then
    for (( j=dbg_index+1; j<${#args[@]} && dbg_count<2; j++ )); do
      [[ "${args[j]}" =~ ^- ]] && break
      case "${args[j],,}" in
        xtrace)
          declare -gx VAR_DEBUG_TRACE="true"
          . "${script_dir}/0052_debug_trace.sh"
          . "${script_dir}/0053_debug_trace_header.sh"
          debug_trace "$@"
          ;;
        trap)
          declare -gx VAR_DEBUG_TRAP="true"
          . "${script_dir}/0054_debug_trap.sh"
          . "${script_dir}/0055_debug_trap_header.sh"
          trap 'debug_trap' DEBUG
          ;;
        *)
          arg_mismatch "Invalid debug option: '${args[j]}'." ;;
      esac
      (( dbg_count++ ))
    done

    if (( dbg_count == 0 )); then arg_mismatch "--debug MUST NOT be empty."; fi
    if (( dbg_count > 2 )); then arg_mismatch "--debug accepts at most two options (XTRACE, TRAP)."; fi
  fi
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
