#!/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 format the respective partition on each entry of 'ARY_FORMT_MOUNT_PATHS'.
# Globals:
#   ARY_FORMT_MOUNT_PATHS
#   DIR_LOG
#   HMP_PATH_DEV_PART
#   HMP_PATH_FSUUID
#   NL
#   VAR_RECIPE_STRING
#   VAR_SETUP_PART
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
partition_formatting() {
  ### Declare Arrays, HashMaps, and Variables.
  # shellcheck disable=SC2034
  declare -Ag HMP_PATH_FSUUID        # Used in: 3290() - [Mount Path:Filesystem UUID].
                                     # Used in: 4200() - [Mount Path:Filesystem UUID].
                                     # Used in: 4210() - [Mount Path:Filesystem UUID].
  declare     var_dev="" var_dev_part="" var_dev="" \
              var_encryption_enable="" var_encryption_label="" var_format_path="" var_fs_btrfs_checksum="" \
              var_fs_btrfs_compress="" var_fs_btrfs_mdup="" var_fs_label="" var_fs_options="" var_fs_version="" \
              var_node="" var_fs_uuid=""

  declare -a  ary_opts=() ary_fmt_opts=()

  for var_format_path in "${ARY_FORMT_MOUNT_PATHS[@]}"; do

    ### Initialize Arrays and Variables
    ary_opts=(); ary_fmt_opts=()

    ### Generates physical device location.
    var_dev_part="${HMP_PATH_DEV_PART["${var_format_path}"]}"
    var_dev="${var_dev_part//./}"

    ### Extract parameters from YAML.
    var_encryption_enable=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev_part}.encryption.enable"         "${VAR_SETUP_PART}")
    var_fs_btrfs_checksum=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev_part}.filesystem.btrfs.checksum" "${VAR_SETUP_PART}")
    var_fs_btrfs_compress=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev_part}.filesystem.btrfs.compress" "${VAR_SETUP_PART}")
    var_fs_btrfs_mdup=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev_part}.filesystem.btrfs.mdup"         "${VAR_SETUP_PART}")
    var_fs_options=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev_part}.filesystem.options"               "${VAR_SETUP_PART}")
    var_fs_version=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev_part}.filesystem.version"               "${VAR_SETUP_PART}")

    case "${var_format_path,,}" in
      swap|/tmp)
        do_log "info" "file_only" "3240() Partition: '/dev/${var_dev}' ephemeral encryption already prepared in 3220(): '${var_format_path}'."
        ### Nothing more to do here.
        continue
        ;;
    esac

    if [[ "${var_encryption_enable,,}" == "true" ]]; then
      var_encryption_label=$(get_label "${var_format_path}" "${var_fs_version}" "luks")
      var_node="/dev/mapper/${var_encryption_label}"
    else
      var_node="/dev/${var_dev}"
    fi

    var_fs_label=$(get_label "${var_format_path}" "${var_fs_version}" "file")

    case "${var_fs_version,,}" in

      btrfs)
        ary_opts=( -L "${var_fs_label}" -f --csum "${var_fs_btrfs_checksum}" )
        [[ "${var_fs_btrfs_mdup,,}" == "true" ]] && ary_opts+=( -m dup )

        mkfs.btrfs "${ary_opts[@]}" "${var_node}"

        do_log "debug" "file_only" "3240() [mkfs.btrfs ${ary_opts[*]} ${var_node}]."
        do_log "info" "file_only" "3240() Partition: '${var_node}' formatted: 'btrfs' options: '${ary_opts[*]}'."

        echo "Partition: '${var_node}':" >> "${DIR_LOG}/btrfs.log"
        btrfs filesystem show "${var_node}" >> "${DIR_LOG}/btrfs.log"

        var_fs_uuid=$(blkid -s UUID -o value "${var_node}")
        ### Gathering information for '/etc/fstab'-generation in 4040() and '/etc/crypttab'-generation in 4060().
        # shellcheck disable=SC2034
        HMP_PATH_FSUUID["${var_format_path}"]="${var_fs_uuid}"
        ;;

      ext4)
        read -r -a ary_fmt_opts <<< "${var_fs_options}"

        mkfs.ext4 -L "${var_fs_label}" "${ary_fmt_opts[@]}" "${var_node}"

        do_log "debug" "file_only" "3240() [mkfs.ext4 -L ${var_fs_label} ${ary_fmt_opts[*]} ${var_node}]."
        do_log "info" "file_only" "3240() Partition: '${var_node}' formatted: 'ext4' options: '${ary_fmt_opts[*]}'."

        echo "Partition: '${var_node}':" >> "${DIR_LOG}/ext4.log"
        tune2fs -l "${var_node}" >> "${DIR_LOG}/ext4.log"

        var_fs_uuid=$(blkid -s UUID -o value "${var_node}")
        ### Gathering information for '/etc/fstab'-generation in 4040() and '/etc/crypttab'-generation in 4060().
        # shellcheck disable=SC2034
        HMP_PATH_FSUUID["${var_format_path}"]="${var_fs_uuid}"
        ;;

      fat32)
        mkfs.fat -F 32 -n "${var_fs_label}" "${var_node}"

        do_log "debug" "file_only" "3240() [mkfs.fat -F 32 -n ${var_fs_label} ${var_node}]."
        do_log "info" "file_only" "3240() Partition: '${var_node}' formatted: 'FAT32'."

        var_fs_uuid=$(blkid -s UUID -o value "${var_node}")
        ### Gathering information for '/etc/fstab'-generation in 4040() and '/etc/crypttab'-generation in 4060().
        # shellcheck disable=SC2034
        HMP_PATH_FSUUID["${var_format_path}"]="${var_fs_uuid}"
        ;;

      *)
        do_log "error" "file_only" "3240() Unsupported filesystem format: '${var_fs_version}'."
        continue
        ;;

    esac

    var_dev="${var_dev_part%.*}"
    lsblk -o NAME,MAJ:MIN,FSTYPE,FSVER,SIZE,UUID,MOUNTPOINT,PATH "/dev/${var_dev}" >| "${DIR_LOG}/${var_dev}_overview_3240.log"
    printf "%b" "${NL}" >> "${DIR_LOG}/${var_dev}_overview_3240.log"
    lsblk "/dev/${var_dev}" >> "${DIR_LOG}/${var_dev}_overview_3240.log"

  done

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