#!/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: LicenseRef-CNCL-1.1 OR LicenseRef-CCLA-1.1
# 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}"

#######################################
# Cleanup wrapper on the traps on 'ERR' and 'EXIT'.
# Globals:
#   GNUPGHOME
#   LOG_ERROR
#   VAR_CDLB_INSIDE_RUNNER
#   VAR_EARLY_DEBUG
#   VAR_HANDLER_BUILD_DIR
#   VAR_KERNEL_INF
#   VAR_KERNEL_SRT
#   VAR_KERNEL_TMP
#   VAR_NOTES
#   VAR_TMP_SECRET
#   VAR_WORKDIR
# Arguments:
#   1 : ${trap_on_exit_code} of trap_on_exit()
# Returns:
#   0: on success
#######################################
clean_up() {
  declare clean_exit_code="$1" fs_type="" _old_nullglob="" _old_dotglob="" _old_failglob=""

  ### Enable nullglob/dotglob, disable failglob for safe globbing.
  _old_nullglob="$(shopt -p nullglob || true)"
  _old_dotglob="$( shopt -p dotglob  || true)"
  _old_failglob="$(shopt -p failglob || true)"

  shopt -s nullglob dotglob
  shopt -u failglob

  if [[ -e /dev/mapper/crypt_liveiso ]]; then
    cryptsetup close crypt_liveiso || true
  fi

  rm -f -- "${VAR_KERNEL_INF}"
  rm -f -- "${VAR_KERNEL_SRT}"
  rm -f -- "${VAR_KERNEL_TMP}"
  rm -f -- "${VAR_NOTES}"

  ### Release advisory lock on FD 127.
  flock -u 127

  ### Close file descriptor 127.
  exec 127>&-

  ### Remove the lockfile artifact.
  rm -f /run/lock/ciss_live_builder.lock

  ### Removes the error log on clean exit.
  if (( clean_exit_code == 0 )); then rm -f -- "${LOG_ERROR}"; fi

  ### Cleaning TCP wrapper artifacts.
  if [[ -f "${VAR_WORKDIR}/hosts.allow" ]]; then
    rm -f "${VAR_WORKDIR}/hosts.allow"
  fi
  if [[ -f "${VAR_WORKDIR}/hosts.deny" ]]; then
    rm -f "${VAR_WORKDIR}/hosts.deny"
  fi

  ### Kill gpg-agent and remove artifacts securely.
  if [[ "${VAR_CDLB_INSIDE_RUNNER}" != "true" ]]; then

    if [[ -n "${GNUPGHOME:-}" && -d "${GNUPGHOME}" ]]; then

      gpgconf --kill gpg-agent >/dev/null 2>&1 || true

      fs_type="$(stat -f -c %T "${GNUPGHOME}" 2>/dev/null || echo "GNUPGHOME: unknown fs.")"

      if [[ "${fs_type}" == "tmpfs" || "${fs_type}" == "ramfs" ]]; then

        rm -rf --one-file-system -- "${GNUPGHOME}" 2>/dev/null || true

      else

        chmod -R u+rwX "${GNUPGHOME}" >/dev/null 2>&1 || true
        find "${GNUPGHOME}" -type f -exec shred -fuz -n 2 -- {} + 2>/dev/null || true
        find "${GNUPGHOME}" \( -type s -o -type p -o -type l \) -delete 2>/dev/null || true
        rm -rf --one-file-system -- "${GNUPGHOME}" 2>/dev/null || true

      fi

    fi

  fi

  ### No tracing for security reasons ------------------------------------------------------------------------------------------
  [[ "${VAR_EARLY_DEBUG}" == "true" ]] && set +x

  ### Removes secrets securely.
  # shellcheck disable=SC2312
  find "${VAR_TMP_SECRET}" -xdev -type f -print0 | xargs -0 --no-run-if-empty shred -fzu -n 5 --
  find "${VAR_TMP_SECRET}" -xdev -depth -type d -empty -delete

  ### Securely shred all regular files below ./includes.chroot, then remove empty dirs.
  if [[ -d "${VAR_HANDLER_BUILD_DIR}/config/includes.chroot" ]]; then

    # shellcheck disable=SC2312
    find "${VAR_HANDLER_BUILD_DIR}/config/includes.chroot" -xdev -type f -print0 | xargs -0 --no-run-if-empty shred -fzu -n 5 --

    ### Remove empty directories (bottom-up).
    find "${VAR_HANDLER_BUILD_DIR}/config/includes.chroot" -depth -xdev -type d -empty -delete

  fi

  ### Delete all files and directories below ./chroot.
  if [[ -d "${VAR_HANDLER_BUILD_DIR}/chroot" ]]; then

    rm -rf "${VAR_HANDLER_BUILD_DIR}/chroot"

  fi

  ### Turn on tracing again ----------------------------------------------------------------------------------------------------
  [[ "${VAR_EARLY_DEBUG}" == "true" ]] && set -x

  eval "${_old_nullglob}" 2>/dev/null || true
  eval "${_old_dotglob}"  2>/dev/null || true
  eval "${_old_failglob}" 2>/dev/null || true

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