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

#######################################
# '/etc/crypttab' entry writer and logger.
# Globals:
#   TARGET
# Arguments:
#   1: Encryption Label
#   2: LUKS Container UUID
#   3: Keyfile or none
#   4: LUKS Options
# Returns:
#   0: on success
#######################################
write_crypttab() {
  declare write_label="$1" write_dev="$2" write_key_file="$3" write_opts="$4"

  printf "%-43s%-46s%-40s%s \n" "${write_label}" "${write_dev}" "${write_key_file}" "${write_opts}" >> "${TARGET}/etc/crypttab"
  do_log "info" "file_only" "4210() crypttab entry generated: [${write_label} ${write_dev} ${write_key_file} ${write_opts}]."

  return 0
}

#######################################
# Generate target '/etc/crypttab' entries.
# Globals:
#   HMP_EPHEMERAL_ENCLABEL
#   HMP_PATH_ENCLABEL
#   HMP_PATH_FSUUID
#   HMP_PATH_LUKSUUID
#   TARGET
#   VAR_DROPBEAR
#   VAR_NUKE
#   VAR_VERSION
# Arguments:
#  None
# Returns:
#   0: on success
#######################################
generate_crypttab() {
  ### Declare Arrays, HashMaps, and Variables.
  declare     var_key="" var_encryption_label="" var_luks_uuid="" var_ephemeral_enclabel="" var_host_uuid=""

  ensure_lowercase "VAR_DROPBEAR"

  ### Generate '${TARGET}/etc/crypttab' header.
  : >| "${TARGET}/etc/crypttab"
  chmod 0600 "${TARGET}/etc/crypttab"

  cat << EOF >> "${TARGET}/etc/crypttab"
# 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

# /etc/crypttab                : Generated by CISS.debian.installer ${VAR_VERSION}
# Architecture                 : ${VAR_ARCHITECTURE}
# Distribution                 : ${VAR_CODENAME}

# Static file system information: '/etc/crypttab'.
#
# Basic rule: 'discard' / 'nodiscard' are normally only set in '/etc/crypttab' when LUKS/dm-crypt is in use. Options like
# 'discard=async' or similar are typically only set in '/etc/fstab' (at the file system level). The crypttab determines whether
# the underlying encrypted device (LUKS/dm-crypt) passes TRIM commands to the physical drive or not. The '/etc/fstab' determines
# whether and how the file system itself generates the discard operations and sends them down through the LUKS layer.
#
# RECOMMENDED: 'discard' enables the TRIM commands to be forwarded by the dm-crypt layer to the SSD/physical device. If ones do
# not specify discard in the '/etc/crypttab', dm-crypt blocks TRIM by default. This would render a discard in the '/etc/fstab'
# ineffective.
#
# <name>                                   <device>                                      <password-file-or-none>                 <options>

EOF

  ### Generate '${TARGET}/etc/crypttab' entries.
  for var_key in "${!HMP_PATH_LUKSUUID[@]}"; do

    var_encryption_label="${HMP_PATH_ENCLABEL["${var_key}"]}"
    var_luks_uuid="${HMP_PATH_LUKSUUID["${var_key}"]}"

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

      if [[ "${var_key}" == "/" ]]; then

        mkdir -p "${TARGET}/etc/initramfs-tools/files"
        mkdir -p "${TARGET}/usr/lib/cryptsetup/scripts"

        ### Install the script to be called inside initramfs environment for unlocking LUKS and NUKE Devices.
        install -m 0755 -o root -g root "${VAR_SETUP_PATH}/includes/target/etc/initramfs-tools/files/unlock_wrapper.sh" \
          "${TARGET}/etc/initramfs-tools/files/"
        install -m 0755 -o root -g root "${VAR_SETUP_PATH}/includes/target/etc/initramfs-tools/files/unlock_wrapper.sh" \
          "${TARGET}/lib/cryptsetup/scripts/"

        write_crypttab "${var_encryption_label}" "UUID=${var_luks_uuid}" "none" "luks,discard,initramfs,keyscript=/lib/cryptsetup/scripts/unlock_wrapper.sh"

      else

        write_crypttab "${var_encryption_label}" "UUID=${var_luks_uuid}" "none" "luks,discard,initramfs"

      fi

    else

      write_crypttab "${var_encryption_label}" "UUID=${var_luks_uuid}" "none" "luks,discard"

    fi

  done

  ### Generate '${TARGET}/etc/crypttab' ephemeral entries.
  for var_key in "${!HMP_EPHEMERAL_ENCLABEL[@]}"; do

    var_ephemeral_enclabel="${HMP_EPHEMERAL_ENCLABEL["${var_key}"]}"
    var_host_uuid="${HMP_PATH_FSUUID["${var_key}"]}"

    case "${var_key}" in

      SWAP)
        write_crypttab "${var_ephemeral_enclabel}" "UUID=${var_host_uuid}" "/dev/random" "swap,offset=2048,cipher=aes-xts-plain64,size=512,sector-size=4096"
        ;;

      /tmp)
        write_crypttab "${var_ephemeral_enclabel}" "UUID=${var_host_uuid}" "/dev/random" "offset=2048,cipher=aes-xts-plain64,size=512,sector-size=4096,tmp=ext4"
        ;;

      *)
        do_log "error" "file_only" "4060() Only 'SWAP' and '/tmp' are valid Partitions for Ephemeral Encryption. Given value was: '${var_key}'."
        continue
        ;;

    esac

  done

  cat << 'EOF' >> "${TARGET}/etc/crypttab"

# vim: number et ts=2 sw=2 sts=2 ai tw=200 ft=sh
EOF

  guard_dir && return 0
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
