#!/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.
# Globals:
#   LOG_VAR
#   VAR_DEBUG_TRACE
#   VAR_DEBUG_TRAP
# Arguments:
#   None
#######################################
pre_scan_debug() {
  declare -a args=("$@")
  declare -i dbg_index=-1 dbg_count=0 i=0 j=0

  for i in "${!args[@]}"; do

    if [[ "${args[i]}" == "-d" || "${args[i]}" == "--debug" ]]; then
      dbg_index=${i}

      declare -grx LOG_VAR="${DIR_LOG}/ciss_debian_installer_$$_var.log"
      touch "${LOG_VAR}" && chmod 0600 "${LOG_VAR}"

      # shellcheck disable=SC2155
      declare -gx VAR_DUMP_VARS_INITIAL=$(mktemp var_dump_vars_initial.XXXXXXXX)
      VAR_DUMP_VARS_INITIAL=$(readlink -f "${VAR_DUMP_VARS_INITIAL}")

      # shellcheck disable=SC2155
      declare -gx VAR_DUMP_VARS_FINAL=$(mktemp var_dump_vars_final.XXXXXXXX)
      VAR_DUMP_VARS_FINAL=$(readlink -f "${VAR_DUMP_VARS_FINAL}")

      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"
          debug_trace "$@"
          ;;

        trap)
          declare -gx VAR_DEBUG_TRAP="true"
          initialize_debug_trap
          trap 'debug_trap' DEBUG
          ;;

        *)
          arg_mismatch "Invalid debug option: '${args[j]}'." ;;

      esac

      dbg_count=$(( dbg_count + 1 ))

    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
