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

#######################################
# Configure target system for chroot.
# Globals:
#   ERR_CHRT_MOUNTS
#   TARGET
# Arguments:
#   None
# Returns:
#   ERR_CHRT_MOUNTS
#   0: on success
#######################################
configure_system() {

  ### Notes
  # --rbind: recursive binding.
  # --make-rslave: In this case, the mount point is marked as 'slave'.
  # This means changes to the source mount (e.g., /proc) are propagated to the target mount (e.g., "${TARGET}"/proc).
  # Conversely, changes to the target mount are not propagated back to the source mount.
  # This mode is necessary to avoid problems with double or erroneous propagation effects in chroot or container environments.

  declare var_src var_dst
  declare -a ary_mounts=(proc sys dev run)

  for var_src in "${ary_mounts[@]}"; do
    var_dst="${TARGET}/${var_src}"
    mkdir -p "${var_dst}"

    if ! mount --make-rslave --rbind "/${var_src}" "${var_dst}"; then
      do_log "emergency"  "false"  "Failed: 'mount --make-rslave --rbind /${var_src} ${var_dst}'."
      return "${ERR_CHRT_MOUNTS}"
    fi

    do_log "info"  "true"  "Success: 'mount --make-rslave --rbind /${var_src} ${var_dst}'."

  done

  if ! do_in_target "${TARGET}" mkdir -p /etc/systemd/system/multi-user.target.wants; then
    return "${ERR_CHRT_MOUNTS}"
  fi

  do_log "info" "true" "Command: 'mkdir -p /etc/systemd/system/multi-user.target.wants' executed in: '${TARGET}'."
  return 0
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
