#!/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}"

#######################################
# Trap function to be called on 'EXIT'.
# Globals:
#   ERRCMMD
#   ERRCODE
#   ERRFUNC
#   ERRLINE
#   ERRSCRT
#   ERRTRAP
#   VAR_EARLY_DEBUG
# Arguments:
#   1: $?
#   2: ${BASH_SOURCE[0]}
#   3: ${LINENO}
#   4: ${FUNCNAME[0]:-main}
#   5: ${BASH_COMMAND}
#######################################
trap_on_exit() {
  declare errcode="${ERRCODE:-$1}"
  declare errscrt="${ERRSCRT:-$2}"
  declare errline="${ERRLINE:-$3}"
  declare errfunc="${ERRFUNC:-$4}"
  declare errcmmd="${ERRCMMD:-$5}"

  trap - DEBUG ERR EXIT INT TERM

  ### Defensive shell behavior inside trap.
  set +e +o pipefail

  if (( errcode == 0 )); then

    if "${VAR_EARLY_DEBUG}"; then dump_user_vars; fi

    clean_up "${errcode}"

    print_scr_exit "${errcode}"

    exit "${errcode}"

  else

    if [[ ! "${ERRTRAP}" == "true" ]]; then

      if "${VAR_EARLY_DEBUG}"; then dump_user_vars; fi

      clean_up "${errcode}"

      print_scr_exit_non_zero "${errcode}" "${errscrt}" "${errline}" "${errfunc}" "${errcmmd}"

    fi

    exit "${errcode}"

  fi
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f trap_on_exit

#######################################
# Print success message for trap on 'EXIT' on 'stdout'.
# Globals:
#   LOG_DEBUG
#   LOG_VAR
#   SECONDS
#   VAR_EARLY_DEBUG
#   VAR_GIT_REL
#   VAR_HANDLER_BUILD_DIR
#   VAR_SCRIPT_SUCCESS
#   VAR_SYSTEM
#   VAR_VERSION
#   VAR_VER_BASH
#   VAR_VER_DS
#   VAR_VER_LB
# Arguments:
#   1: ${errcode} of trap_on_exit()
#######################################
print_scr_exit() {
  declare -r var_print_scr_exit_code="$1"

  if (( var_print_scr_exit_code == 0 )); then

    if [[ "${VAR_SCRIPT_SUCCESS}" == "true" ]]; then

      printf "\n"
      printf "\e[92m✅ CISS.debian.live.builder Script successfully completed. \e[0m\n"
      printf "\e[92m✅ Git Commit             : %s \e[0m\n" "${VAR_GIT_REL}"
      printf "\e[92m✅ Version                : %s \e[0m\n" "${VAR_VERSION}"
      printf "\e[92m✅ Hostsystem             : %s \e[0m\n" "${VAR_SYSTEM}"
      printf "\e[92m✅ Bash                   : %s \e[0m\n" "${VAR_VER_BASH}"
      printf "\e[92m✅ Live-Build             : %s \e[0m\n" "${VAR_VER_LB}"
      printf "\e[92m✅ Debootstrap            : %s \e[0m\n" "${VAR_VER_DS}"
      printf "\e[92m✅ Aide Initial DB at     : %s \e[0m\n" "${VAR_HANDLER_BUILD_DIR}/.integrity/"
      printf "\e[92m✅ Exited with Status     : %s \e[0m\n" "${var_print_scr_exit_code}"
      printf "\n"

      if [[ "${VAR_EARLY_DEBUG}" == "true" ]]; then

        printf "\e[92m✅ Script Runtime         : %s \e[0m\n" "${SECONDS}"
        printf "\e[92m✅ Vars Dump saved at     : %s \e[0m\n" "${LOG_VAR}"
        printf "\e[92m✅ Debug Log saved at     : %s \e[0m\n" "${LOG_DEBUG}"
        printf "\e[92m✅ batcat --pager='less -r' %s \e[0m\n" "${LOG_DEBUG}"
        printf "\n"

      fi

      printf "\e[95m💷 Please consider donating to my work at: \e[0m\n"
      printf "\e[95m🔗 https://coresecret.eu/spenden/          \e[0m\n"
      printf "\n"

    fi

  fi
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f print_scr_exit

#######################################
# Trap on 'EXIT' handler for 'non-0' exit-code.
# Globals:
#   BASHOPTS
#   EPOCHREALTIME
#   ERRCMMD
#   ERRCODE
#   ERRFUNC
#   ERRLINE
#   ERRSCRT
#   EUID
#   LOG_DEBUG
#   LOG_ERROR
#   LOG_VAR
#   NL
#   SECONDS
#   SHELLOPTS
#   UID
#   VAR_ARG_SANITIZED
#   VAR_EARLY_DEBUG
#   VAR_GIT_REL
#   VAR_PARAM_COUNT
#   VAR_PARAM_STRNG
#   VAR_SYSTEM
#   VAR_VERSION
#   VAR_VER_BASH
#   VAR_VER_DS
#   VAR_VER_LB
# Arguments:
#   1: $?
#   2: ${BASH_SOURCE[0]}
#   3: ${LINENO}
#   4: ${FUNCNAME[0]:-main}
#   5: ${BASH_COMMAND}
#######################################
print_scr_exit_non_zero() {
  declare errcode="${ERRCODE:-$1}"
  declare errscrt="${ERRSCRT:-$2}"
  declare errline="${ERRLINE:-$3}"
  declare errfunc="${ERRFUNC:-$4}"
  declare errcmmd="${ERRCMMD:-$5}"

  printf "\e[91m❌ Trap on 'EXIT'         : CISS.debian.live.builder Script failed. \e[0m\n" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌                        : This was most probably caused by an unbound variable. \e[0m\n" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Git Commit             : %s \e[0m\n" "${VAR_GIT_REL}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Version                : %s \e[0m\n" "${VAR_VERSION}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Epoch                  : %s \e[0m\n" "${EPOCHREALTIME}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Bash                   : %s \e[0m\n" "${VAR_VER_BASH}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Live-Build             : %s \e[0m\n" "${VAR_VER_LB}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Debootstrap            : %s \e[0m\n" "${VAR_VER_DS}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ UID                    : %s \e[0m\n" "${UID}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ EUID                   : %s \e[0m\n" "${EUID}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Hostsystem             : %s \e[0m\n" "${VAR_SYSTEM}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Error                  : %s \e[0m\n" "${errcode}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Line                   : %s \e[0m\n" "${errline}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Script                 : %s \e[0m\n" "${errscrt}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Function               : %s \e[0m\n" "${errfunc}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Command                : %s \e[0m\n" "${errcmmd}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Script Runtime         : %s \e[0m\n" "${SECONDS}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Arguments Counter      : %s \e[0m\n" "${VAR_PARAM_COUNT}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Arguments Original     : %s \e[0m\n" "${VAR_PARAM_STRNG}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Arguments Sanitized    : %s \e[0m\n" "${VAR_ARG_SANITIZED}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Bashopts               : %s \e[0m\n" "${BASHOPTS}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Shellopts              : %s \e[0m\n" "${SHELLOPTS}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ Error Log saved at     : %s \e[0m\n" "${LOG_ERROR}" | tee -a "${LOG_ERROR}"
  printf "\e[91m❌ batcat --pager='less -r' %s \e[0m\n" "${LOG_ERROR}" | tee -a "${LOG_ERROR}"

  if "${VAR_EARLY_DEBUG}"; then

    printf "\e[91m❌ Vars Dump saved at     : %s \e[0m\n" "${LOG_VAR}" | tee -a "${LOG_ERROR}"
    printf "\e[91m❌ Debug Log saved at     : %s \e[0m\n" "${LOG_DEBUG}" | tee -a "${LOG_ERROR}"
    printf "\e[91m❌ batcat --pager='less -r' %s \e[0m\n" "${LOG_DEBUG}" | tee -a "${LOG_ERROR}"

  fi

  print_stacktrace
  printf "%b" "${NL}"
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f print_scr_exit_non_zero
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
