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

#######################################
# Validates var_mount_path to be processed.
# Arguments:
#   1 var_mount_path
# Returns:
#   0: Skip mounting
#   1: Process mount
#######################################
skip_path() {
  declare -a ary_skip=( "/" "/boot" "/boot/efi" "/recovery" )
  declare p
  for p in "${ary_skip[@]}"; do [[ "$1" == "$p" ]] && return 0; done
  return 1
}

#######################################
# Function to create the mount path and mount the respective device on it.
# Globals:
#   ERR_MOUNTING_DEV
#   TARGET
# Arguments:
#   1: MOUNT_PATH
#   2: MOUNT_DEVICE
#   3: MOUNT_OPTIONS
#######################################
mount_with_dir() {
  declare var_mount_path="$1" var_mount_device="$2" var_mount_options="$3"

  [[ "${var_mount_path}" != "/" ]] && mkdir -p "${TARGET}${var_mount_path}"

  ### Build the command in an array to keep word boundaries intact
  declare -a ary_cmd=(mount)
  [[ -n "${var_mount_options}" ]] && ary_cmd+=("-o" "${var_mount_options}")
  ary_cmd+=("${var_mount_device}" "${TARGET}${var_mount_path}")

  safe_exec "${ary_cmd[@]}" "${ERR_MOUNTING_DEV}" || return
  do_log "info" "false" "Mounted: '${var_mount_device}' on: '${TARGET}${var_mount_path}' (Options='${var_mount_options}')."
}

#######################################
# Device Path Resolver
# Arguments:
#   1: Device
#   2: Partition
#   3: Boolean Encryption
#   4: Encryption Label
#######################################
resolve_device() {
  declare local_var_dev="$1" local_var_partition="$2" local_var_enc_boolean="$3" local_var_enc_label="$4"
  if [[ "${local_var_enc_boolean,,}" == true ]]; then
    printf '/dev/mapper/%s' "${local_var_enc_label}"
  else
    printf '/dev/%s%s' "${local_var_dev}" "${local_var_partition}"
  fi
}

#######################################
# Validates btrfs compression algo and level.
# Arguments:
#   1 var_fs_btrfs_compress
#   2 var_fs_btrfs_level
# Returns:
#   0: Valid combination.
#   1: Invalid combination.
#######################################
validate_btrfs_compression() {
  declare var_algo="$1" var_level="$2"
  case "${var_algo}:${var_level}" in
    zstd:|zstd:[0-9]|zstd:1[0-9]|zstd:2[0-2]|lzo:) return 0 ;;
    *) do_log "error" "false" "Invalid btrfs compression '${var_algo}:${var_level}'"; return "${ERR_BTRFS_OPTION}" ;;
  esac
}

#######################################
# Function for mounting all partitions for debootstrap, including the generation of btrfs subvolumes.
# Globals:
#   HMP_MOUNTPATH_DEV
#   TARGET
#   VAR_RECIPE_STRING
#   VAR_SAFE_MNT_BASE
#   VAR_SETUP_PART
# Arguments:
#   None
# Returns:
#   ERR_BTRFS_INITPH
#   ERR_BTRFS_OPTION
#   ERR_BTRFS_SUBVOL
#   ERR_MOUNTING_DEV
#   ERR_MOUNTING_ROOT
#   0: on success
#######################################
mount_partition() {
  ### Mount "/"-filesystem
  declare -r var_mount_path_root="/"

  if [[ -n ${HMP_MOUNTPATH_DEV[$var_mount_path_root]} ]]; then

    mount_with_dir "${var_mount_path_root}" "${HMP_MOUNTPATH_DEV[$var_mount_path_root]}" || return "${ERR_MOUNTING_DEV}"

  else

    do_log "error" "false" "Root-filesystem '${var_mount_path_root}' not found in Hashmap."
    return "${ERR_MOUNTING_ROOT}"

  fi

  ### Ensure order of "/boot" and "/boot/efi"
  declare var_path

  for var_path in "/boot" "/boot/efi"; do

    if [[ -n ${HMP_MOUNTPATH_DEV[${var_path}]} ]]; then

      mount_with_dir "${var_path}" "${HMP_MOUNTPATH_DEV[${var_path}]}" || return "${ERR_MOUNTING_DEV}"

    else

      do_log "info" "false" "Entry '${var_path}' not found in Hashmap."

    fi

  done

  declare var_dev var_part \
    var_fs_btrfs_compress var_fs_btrfs_level var_fs_btrfs_subvolume var_fs_btrfs_snapshot \
    var_encryption_enable var_encryption_label \
    var_fs_label var_fs_options var_fs_version var_mount_path var_mount_options var_mount_optsnap
  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_fs_btrfs_compress=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.btrfs.compress"   "${VAR_SETUP_PART}")
      var_fs_btrfs_level=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.btrfs.level"         "${VAR_SETUP_PART}")
      var_fs_btrfs_subvolume=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.btrfs.subvolume" "${VAR_SETUP_PART}")
      var_fs_btrfs_snapshot=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.btrfs.snapshot"   "${VAR_SETUP_PART}")
      var_encryption_enable=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.enable"           "${VAR_SETUP_PART}")
      var_encryption_label=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.label"             "${VAR_SETUP_PART}")
      var_fs_label=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.label"                     "${VAR_SETUP_PART}")
      var_fs_options=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.options"                 "${VAR_SETUP_PART}")
      var_fs_version=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.version"                 "${VAR_SETUP_PART}")
      var_mount_path=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.mount.path"                         "${VAR_SETUP_PART}")
      var_mount_options=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.mount.options"                   "${VAR_SETUP_PART}")
      var_mount_optsnap=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.mount.optsnap"                   "${VAR_SETUP_PART}")

      ### Skip already mounted paths ("/", "/boot", "/boot/efi") and skip ("/recovery")
      skip_path "${var_mount_path}" && continue

      if [[ "${var_mount_path}" == "SWAP" ]]; then

        cryptsetup open --type plain --key-file /dev/random \
          --offset 2048 --cipher aes-xts-plain64 --key-size 512 \
          --sector-size 4096 "/dev/disk/by-label/${var_fs_label}" "${var_encryption_label}"
        mkswap "/dev/mapper/${var_encryption_label}"
        swapon "/dev/mapper/${var_encryption_label}"
        do_log "info" "false" "Mounted: '${var_mount_path}' on: '/dev/mapper/${var_encryption_label}'."
        continue

      elif [[ "${var_mount_path}" == "/tmp" ]]; then

        cryptsetup open --type plain --key-file /dev/random \
          --offset 2048 --cipher aes-xts-plain64 --key-size 512 \
          --sector-size 4096 "/dev/disk/by-label/${var_fs_label}" "${var_encryption_label}"
        mkdir -p "${TARGET}/tmp"
        mkfs.ext4 "/dev/mapper/${var_encryption_label}"

        ### Build the command in an array to keep word boundaries intact
        declare -a ary_cmd2=(mount)
        [[ -n "${var_mount_options}" ]] && ary_cmd2+=("-o" "${var_mount_options}")
        ary_cmd2+=("/dev/mapper/${var_encryption_label}" "${TARGET}${var_mount_path}")

        safe_exec "${ary_cmd2[@]}" "${ERR_MOUNTING_DEV}" || return "${ERR_MOUNTING_DEV}"
        do_log "info" "false" "Mounted: '${var_mount_path}' on: '/dev/mapper/${var_encryption_label}'."
        continue

      fi

      declare var_resolved_dev
      var_resolved_dev=$(resolve_device "${var_dev}" "${var_part}" "${var_encryption_enable}" "${var_encryption_label}")

      if [[ "${var_fs_version,,}" == btrfs ]]; then

        ### Mount toplevel (subvolid=0) *without* extra options
        declare -a ary_cmd_mount=(mount -o "subvolid=0" "${var_resolved_dev}" "${VAR_SAFE_MNT_BASE}")
        safe_exec "${ary_cmd_mount[@]}" "${ERR_BTRFS_INITPH}" || return "${ERR_BTRFS_INITPH}"

        btrfs subvolume create "${VAR_SAFE_MNT_BASE}"/"${var_fs_btrfs_subvolume}"

        if [[ -n "${var_fs_btrfs_snapshot}" ]]; then
          btrfs subvolume create "${VAR_SAFE_MNT_BASE}"/"${var_fs_btrfs_snapshot}" || return "${ERR_BTRFS_SUBVOL}"
        fi

        umount "${VAR_SAFE_MNT_BASE}"

      fi

      case "${var_fs_version,,}:${var_encryption_enable,,}" in
        btrfs:*)
          validate_btrfs_compression "${var_fs_btrfs_compress}" "${var_fs_btrfs_level}" || return "${ERR_BTRFS_OPTION}"
          declare var_btrfs_compression_options="compress=${var_fs_btrfs_compress}:${var_fs_btrfs_level}"
          [[ -n "${var_mount_options}" ]] && var_btrfs_compression_options+=",${var_mount_options}"
          mount_with_dir "${var_mount_path}" "${var_resolved_dev}" "${var_btrfs_compression_options}" || return "${ERR_MOUNTING_DEV}"
          if [[ -n "${var_fs_btrfs_snapshot}" ]]; then
            mkdir -p "${TARGET}${var_mount_path}/.snapshots"
            mount -o "${var_mount_optsnap}" "${var_resolved_dev}" "${TARGET}${var_mount_path}/.snapshots"
          fi
          ;;
        ext4:*)
          mount_with_dir "${var_mount_path}" "${var_resolved_dev}" "${var_mount_options}" || return "${ERR_MOUNTING_DEV}"
          ;;
        *) do_log "error" "false" "Unsupported fs/encryption combination."
           return "${ERR_MOUNTING_DEV}" ;;
      esac

    done

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