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

#######################################
# Function to encrypt the respective partition on each device according to the chosen recipe string.
# Globals:
#   DIR_BAK
#   DIR_CNF
#   HMP_EPHEMERAL_DEV
#   HMP_EPHEMERAL_ENCLABEL
#   HMP_EPHEMERAL_FS_LABEL
#   HMP_PATH_ENCLABEL
#   HMP_PATH_LUKSUUID
#   VAR_CRYPT_ROOT
#   VAR_RECIPE_STRING
#   VAR_SETUP_PART
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
partition_encryption() {
  ### Declare Arrays and Variables.
  declare -Agx HMP_EPHEMERAL_DEV HMP_EPHEMERAL_ENCLABEL HMP_EPHEMERAL_FS_LABEL HMP_PATH_LUKSUUID HMP_PATH_ENCLABEL
  declare var_dev var_part \
    var_encryption_enable var_encryption_ephemeral var_encryption_integrity var_encryption_nuke var_encryption_cipher \
    var_encryption_hash var_encryption_iter var_encryption_key var_encryption_label var_encryption_meta \
    var_encryption_pbkdf var_encryption_rng var_filesystem_label var_mount_path var_uuid
  declare -a ary_devs ary_parts

  ### Iterate over all devices in the recipe.
  readarray -t ary_devs < <(yq e -r ".recipe.${VAR_RECIPE_STRING}.dev | keys | .[]" "${VAR_SETUP_PART}")
  for var_dev in "${ary_devs[@]}"; do

    ### Iterate over all partitions for this device.
    readarray -t ary_parts < <(yq e -r ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev} | keys | .[]" "${VAR_SETUP_PART}")
    for var_part in "${ary_parts[@]}"; do

      ### Extract parameters from YAML.
      var_encryption_enable=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.enable"       "${VAR_SETUP_PART}")
      var_encryption_ephemeral=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.ephemeral" "${VAR_SETUP_PART}")
      var_encryption_integrity=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.integrity" "${VAR_SETUP_PART}")
      var_encryption_nuke=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.nuke"           "${VAR_SETUP_PART}")
      var_encryption_cipher=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.cipher"       "${VAR_SETUP_PART}")
      var_encryption_hash=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.hash"           "${VAR_SETUP_PART}")
      var_encryption_iter=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.itertime"       "${VAR_SETUP_PART}")
      var_encryption_key=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.key"             "${VAR_SETUP_PART}")
      var_encryption_label=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.label"         "${VAR_SETUP_PART}")
      var_encryption_meta=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.metadatasize"   "${VAR_SETUP_PART}")
      var_encryption_pbkdf=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.pbkdf"         "${VAR_SETUP_PART}")
      var_encryption_rng=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.rng"             "${VAR_SETUP_PART}")
      var_filesystem_label=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.label"         "${VAR_SETUP_PART}")
      var_mount_path=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.mount.path"                     "${VAR_SETUP_PART}")

      if [[ "${var_encryption_enable,,}" != "true" ]]; then
        continue
      fi

      declare -a ary_luks_opts=(
        --key-file="${DIR_CNF}/password.txt"
        --type luks2
        --cipher "${var_encryption_cipher}"
        --hash "${var_encryption_hash}"
        --iter-time "${var_encryption_iter}"
        --key-size "${var_encryption_key}"
        --label "${var_encryption_label}"
        --luks2-metadata-size "${var_encryption_meta}"
        --pbkdf "${var_encryption_pbkdf}"
        --"${var_encryption_rng}"
        --batch-mode --verbose
      )

      [[ "${var_encryption_integrity,,}" == "true" ]] && ary_luks_opts+=(--integrity hmac-sha512)

      if [[ "${var_encryption_ephemeral,,}" == "true" ]]; then

        case "${var_mount_path}" in

          SWAP|/tmp)

            mkfs.ext4 -L "${var_filesystem_label}" "/dev/${var_dev}${var_part}" 1M
            do_log "info" "true" "Ephemeral: '${var_mount_path}' prepared on: '/dev/${var_dev}${var_part}'."

            HMP_EPHEMERAL_DEV["${var_mount_path}"]="/dev/${var_dev}${var_part}"
            HMP_EPHEMERAL_ENCLABEL["${var_mount_path}"]="${var_encryption_label}"
            HMP_EPHEMERAL_FS_LABEL["${var_mount_path}"]="${var_filesystem_label}"
            do_log "info" "true" "Stored in HashMap [HMP_EPHEMERAL_DEV]     : '${var_mount_path}' -> '${HMP_EPHEMERAL_DEV["${var_mount_path}"]}'"
            do_log "info" "true" "Stored in HashMap [HMP_EPHEMERAL_ENCLABEL]: '${var_mount_path}' -> '${HMP_EPHEMERAL_ENCLABEL["${var_mount_path}"]}'"
            continue
            ;;

          *)
            do_log "error" "true" "Invalid mount path: '${var_mount_path}' for partition: '/dev/${var_dev}${var_part}'."
            continue
            ;;

        esac

      fi

      cryptsetup luksFormat "${ary_luks_opts[@]}" "/dev/${var_dev}${var_part}"

      if [[ "${var_encryption_integrity,,}" == "true" ]]; then

        do_log "info" "false" "Partition: '/dev/${var_dev}${var_part}' dm-integrity encrypted."

      else

        do_log "info" "false" "Partition: '/dev/${var_dev}${var_part}' encrypted."

      fi

      if [[ "${var_encryption_nuke,,}" == "true" ]]; then

        cryptsetup luksAddKey \
          --key-file="${DIR_CNF}/password.txt" \
          --new-keyfile="${DIR_CNF}/password_nuke.txt" \
          --new-key-slot 31 \
          --batch-mode --verbose \
          "/dev/${var_dev}${var_part}"

          do_log "info" "false" "Partition: '/dev/${var_dev}${var_part}' 'Nuke-Key' added."

      fi

      cryptsetup luksHeaderBackup --header-backup-file="${DIR_BAK}/luks_header_${var_dev}${var_part}.bak" "/dev/${var_dev}${var_part}"
      do_log "info" "false" "Partition: '/dev/${var_dev}${var_part}' LUKS Header saved: '${DIR_BAK}/luks_header_${var_dev}${var_part}.bak'."

      ### Opening encrypted container.
      cryptsetup luksOpen "/dev/${var_dev}${var_part}" \
        --key-file="${DIR_CNF}/password.txt" \
        "${var_encryption_label}"
      do_log "info" "false" "Partition: '/dev/${var_dev}${var_part}' opened as '/dev/mapper/${var_encryption_label}'."

      ### Store UUID of the LUKS container.
      var_uuid=$(blkid -s UUID -o value "/dev/mapper/${var_encryption_label}")
      # shellcheck disable=SC2155
      [[ "${var_mount_path}" == "/" ]] && declare -grx VAR_CRYPT_ROOT="${var_uuid}"
      [[ "${var_mount_path}" == "/recovery" ]] && declare -grx VAR_CRYPT_RECOVERY="${var_uuid}"
      HMP_PATH_LUKSUUID["UUID_${var_mount_path}"]="${var_uuid}"
      HMP_PATH_ENCLABEL["LABEL_${var_mount_path}"]="${var_encryption_label}"

    done

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