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

#######################################
# EFI System Partition | EF00 | UEFI Bootloader (ESP, FAT32)
# BIOS Boot Partition  | EF02 | BIOS Bootloader area (GRUB)
# Linux SWAP           | 8200 | Linux Swap
# Linux ext4/btrfs     | 8300 | Linux Filesystem (root, home)
#######################################

#######################################
# Function that generates each partition on each device according to the chosen recipe string and collects information about:
# - the mount path and whether to mount or not and in which order mounting must be done.
# - LUKS encryption enabled.
# - Specific device partition data for each mount path.
# Globals:
#   ARY_FSTAB_MOUNT_PATHS
#   DIR_LOG
#   HMP_FSTAB_MOUNT_FTYPE
#   HMP_PATH_PARTUUID
#   VAR_RECIPE_FIRMWARE
#   VAR_RECIPE_STRING
#   VAR_RECIPE_TABLE
#   VAR_SETUP_PART
# Arguments:
#   None
# Returns:
#   ERR_PARTITIONTBL
#   ERR_PART_CREATE
#   ERR_PART_READ
#   ERR_TABLE_CREATE
#   ERR_TABLE_DELETE
#   0: on success
#######################################
partitioning() {
  ### Declare Arrays, HashMaps, and Variables.
  # shellcheck disable=SC2034
  declare -Ag HMP_PATH_PARTUUID        # Used in: 3290() - [Mount Path:Partition UUID].
  # shellcheck disable=SC2034
  declare -Ag HMP_FSTAB_MOUNT_FTYPE    # Used in: 4200() - [Mount Path:Filesystem type].
  # shellcheck disable=SC2034
  declare -Ag HMP_PATH_DEV_PART        # Used in: 3220() - [Mount Path:DEV.PARTITION].
                                       # Used in: 3240() - [Mount Path:DEV.PARTITION].
                                       # Used in: 3280() - [Mount Path:DEV.PARTITION].
  # shellcheck disable=SC2034
  declare -ag ARY_CRYPT_MOUNT_PATHS=() # Used in: 3220() - Only entries [/paths] for encryption.
  # shellcheck disable=SC2034
  declare -ag ARY_FORMT_MOUNT_PATHS=() # Used in: 3240() - Only entries [/paths] for filesystem generation.
  # shellcheck disable=SC2034
  declare -ag ARY_FSTAB_MOUNT_PATHS=() # Used in: 4200() - Only entries [/paths] for the '/etc/fstab' generation.
  # shellcheck disable=SC2034
  declare -ag ARY_PATHS_SORTED=()      # Used in: 3280() - All entries [/paths] in a mount ordering scheme.
                                       # Used in: 4200() - All entries [/paths] in a mount ordering scheme.

  declare     var_dev="" var_part="" \
              var_begin="" var_boot="" var_encryption="" var_end="" var_end_arg="" var_end_mib="" var_format="" var_fs="" \
              var_label="" var_mount_path="" var_mount_true="" var_pri="" var_uuid=""

  declare -a  ary_devs=() ary_parts=() ary_paths_unsorted=()

  declare -i  i=0 var_dev_size=0 var_dev_end=0 var_sec_size=512

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

    ### All current data for the respective device will be deleted.
    if ! blkdiscard -f "/dev/${var_dev}"; then

      do_log "warn" "file_only" "3200() Partition table: '/dev/${var_dev}' deletion failed with: 'blkdiscard -f' trying 'sgdisk' fallback."

      if command -v sgdisk >/dev/null && sgdisk --zap-all "/dev/${var_dev}"; then

        do_log "debug" "file_only" "3200() [command -v sgdisk >/dev/null && sgdisk --zap-all]."
        do_log "info" "file_only" "3200() Partition table: '/dev/${var_dev}' wiped with 'sgdisk --zap-all'."

      elif dd if=/dev/zero of="/dev/${var_dev}" bs=1M count=8 status=none; then

        do_log "debug" "file_only" "3200() [dd if=/dev/zero of=/dev/${var_dev} bs=1M count=8 status=none]."
        do_log "info" "file_only" "3200() Partition table: '/dev/${var_dev}' overwritten with zeros."

      else

        do_log "fatal" "file_only" "3200() Partition table: '/dev/${var_dev}' deletion failed with: [blkdiscard, sgdisk and dd]."
        return "${ERR_TABLE_DELETE}"

      fi

    else

      do_log "info" "file_only" "3200() Partition table: '/dev/${var_dev}' discarded [blkdiscard -f /dev/${var_dev}]."

    fi

    case "${VAR_RECIPE_TABLE,,}" in

      gpt|mbr)
        if ! parted -s "/dev/${var_dev}" mklabel "${VAR_RECIPE_TABLE,,}"; then

          do_log "fatal" "file_only" "3200() [parted -s /dev/${var_dev} mklabel ${VAR_RECIPE_TABLE,,}] failed."
          do_log "fatal" "file_only" "3200() Partition table: '/dev/${var_dev}' creation failed."
          return "${ERR_TABLE_CREATE}"

        fi

        do_log "info" "file_only" "3200() Partition table: '/dev/${var_dev}' generated: '${VAR_RECIPE_TABLE}'."
        ;;

      *)
        do_log "fatal" "file_only" "3200() No valid partition table chosen. String was '${VAR_RECIPE_TABLE}'."
        return "${ERR_PARTITIONTBL}"
        ;;

    esac

    ### Iterate over all partitions for this device.
    # shellcheck disable=SC2312
    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_begin=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.begin"                  "${VAR_SETUP_PART}")
      var_end=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.end"                      "${VAR_SETUP_PART}")
      var_fs=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.version"        "${VAR_SETUP_PART}")
      var_format=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.format"     "${VAR_SETUP_PART}")
      var_boot=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.bootable"                "${VAR_SETUP_PART}")
      var_pri=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.primary"                  "${VAR_SETUP_PART}")
      var_mount_path=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.mount.path"        "${VAR_SETUP_PART}")
      var_mount_true=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.mount.enable"      "${VAR_SETUP_PART}")
      var_encryption=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.enable" "${VAR_SETUP_PART}")

      ### Assign the start zone of the first partition and skip the first 2 MiB as the best practice.
      if [[ "${var_begin,,}" == "min" ]]; then
        var_begin="2MiB"
      fi

      ### Assign the landing zone of the last partition and reserve 64 MiB for GPT and mdadm binary metadata.
      ### There is no mandatory upper limit, but for particularly critical systems (FDE, RAID-6 setups, dm-integrity, etc.),
      ### more generous reserves between 32 and 64 MiB are recommended.
      if [[ "${var_end,,}" == "max" ]]; then
        var_sec_size=$(blockdev --getpbsz "/dev/${var_dev}")
        var_dev_size=$(blockdev --getsize64 "/dev/${var_dev}")
        var_dev_end=$(( var_dev_size - (64 * 1024 * 1024) ))
        var_end_mib=$(( var_dev_end / 1024 / 1024 ))
        var_end_arg="${var_end_mib}MiB"
      else
        var_end_arg="${var_end}"
      fi

      case "${VAR_RECIPE_TABLE,,}" in

        gpt)

          var_label=$(get_label "${var_mount_path}" "${var_fs}" "part")

          if ! parted -s "/dev/${var_dev}" mkpart "${var_label}" "${var_fs}" "${var_begin}" "${var_end_arg}"; then

            do_log "fatal" "file_only" "3200() [parted -s /dev/${var_dev} mkpart ${var_label} ${var_fs} ${var_begin} ${var_end_arg}] failed."
            do_log "fatal" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' creation failed."
            return "${ERR_PART_CREATE}"

          fi
          ;;

        mbr|msdos)
          if ! parted -s "/dev/${var_dev}" mkpart "${var_pri}" "${var_fs}" "${var_begin}" "${var_end_arg}"; then

            do_log "fatal" "file_only" "3200() [parted -s /dev/${var_dev} mkpart ${var_pri} ${var_fs} ${var_begin} ${var_end_arg}] failed."
            do_log "fatal" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' creation failed."
            return "${ERR_PART_CREATE}"

          fi
          ;;

      esac

      do_log "info" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' generated | begin: '${var_begin}' | end: '${var_end_arg}'."

      ### Assign the correct GPT typecode via sgdisk if the table is GPT.
      if [[ "${VAR_RECIPE_TABLE,,}" == "gpt" ]]; then
        declare typecode="8300" # Default: Linux FS

        case "${var_fs,,}" in

          fat32)
            typecode="EF00" ;;  ### EFI System Partition

          swap)
            typecode="8200" ;;  ### Linux SWAP

          bios)
            typecode="EF02" ;;  ### BIOS Boot Partition

          ext4|btrfs)
            typecode="8300" ;;  ### Linux native FS

          *)
            do_log "warn" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' unknown FS type: '${var_fs}', using default GPT FS '8300'."
            ;;

        esac

        if sgdisk --typecode="${var_part}:${typecode}" "/dev/${var_dev}" &>/dev/null; then

          do_log "info" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' GPT typecode '${typecode}' set for '${var_fs}'."

        else

          do_log "warn" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' GPT typecode '${typecode}' failed to set."

        fi

      fi

      ### Set the bootable flag if necessary.
      if [[ "${var_boot,,}" == "true" ]]; then

        case "${VAR_RECIPE_TABLE,,}:${VAR_RECIPE_FIRMWARE,,}" in

          gpt:uefi|mbr:uefi)

            do_log "info" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' | [${VAR_RECIPE_TABLE^^}:UEFI] no bootable flag required."
            ;;

          gpt:bios|mbr:bios)

            parted -s "/dev/${var_dev}" set "${var_part}" boot on
            do_log "info" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' | [${VAR_RECIPE_TABLE^^}:BIOS] marked as bootable."
            ;;

        esac

      fi

      ### Store PARTUUID of the partition.
      udevadm settle

      for i in {1..10}; do
        var_uuid=$(blkid -s PARTUUID -o value "/dev/${var_dev}${var_part}") && [[ -n "${var_uuid}" ]] && break
        sleep 0.25
      done

      if [[ -z "${var_uuid}" ]]; then
        do_log "fatal" "file_only" "3200() Partition: '/dev/${var_dev}${var_part}' could not read PARTUUID."
        return "${ERR_PART_READ}"
      else
        HMP_PATH_PARTUUID["${var_mount_path}"]="${var_uuid}"
        do_log "debug" "file_only" "3200() [HMP_PATH_PARTUUID]: '${var_mount_path}' -> '${HMP_PATH_PARTUUID["${var_mount_path}"]}'."
      fi

      ### Gathering information for forthcoming modules 32n0().
      # shellcheck disable=SC2034
      HMP_PATH_DEV_PART["${var_mount_path}"]="${var_dev}.${var_part}"

      ### Gathering information for encryption module 3220().
      if [[ "${var_encryption}" == "true" ]]; then
        # shellcheck disable=SC2034
        ARY_CRYPT_MOUNT_PATHS+=("${var_mount_path}")
      fi

      ### Gathering information for filesystem module 3240().
      if [[ "${var_format}" == "true" ]]; then
        # shellcheck disable=SC2034
        ARY_FORMT_MOUNT_PATHS+=("${var_mount_path}")
      fi

      ### Gathering information for mounting module 3280().
      ary_paths_unsorted+=("${var_mount_path}")

      ### Gathering information for '/etc/fstab'-generation in 4200().
      if [[ "${var_mount_true}" == "true" ]]; then
        # shellcheck disable=SC2034
        ARY_FSTAB_MOUNT_PATHS+=("${var_mount_path}")
        do_log "debug" "file_only" "3200() [ARY_FSTAB_MOUNT_PATHS]: '${var_mount_path}'."
        HMP_FSTAB_MOUNT_FTYPE["${var_mount_path}"]="${var_fs}"
        do_log "debug" "file_only" "3200() [HMP_FSTAB_MOUNT_FTYPE]: '${var_mount_path}' -> '${HMP_FSTAB_MOUNT_FTYPE["${var_mount_path}"]}'."
      fi

    done

  lsblk -o NAME,START,SIZE,PHY-SEC,LOG-SEC,ALIGNMENT "/dev/${var_dev}" >| "${DIR_LOG}/${var_dev}_alignment.log"
  sgdisk -p "/dev/${var_dev}" >| "${DIR_LOG}/${var_dev}_info.log"

  done

  ### Prepare mount ordering scheme.
  # shellcheck disable=SC2312
  IFS=$'\n' read -r -d '' -a ARY_PATHS_SORTED < <(printf "%s\n" "${ary_paths_unsorted[@]}" | sort -u | awk 'BEGIN{FS="/"}{print NF, $0}' | sort -n | cut -d' ' -f2- && printf '\0')

  printf "%s\n" "${ary_paths_unsorted[@]}" >| "${DIR_LOG}/mount_paths_unsorted.log"
  printf "%s\n" "${ARY_PATHS_SORTED[@]}" >| "${DIR_LOG}/mount_paths_sorted.log"

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