#!/bin/sh
# bashsupport disable=BP5007
# shellcheck disable=SC2249
# shellcheck shell=sh

# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-11-12; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.live.builder.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.live.builder
# SPDX-Security-Contact: security@coresecret.eu

# Purpose: Open /live/ciss_rootfs.crypt (LUKS) and present its SquashFS as /run/live/rootfs
# Phase  : premount (executed by live-boot inside the initramfs)

set -eu

### Phase gate: run only in the intended live-boot phase -----------------------------------------------------------------------
PHASE="${1:-}"

case "${PHASE}" in

  premount)
    ;;      ### Continue.
  *)
    exit 0  ### Do nothing in other phases.
    ;;

esac

printf "\e[95m[INFO] Starting: [/usr/lib/live/boot/0024-ciss-crypt-squash] ... \n\e[0m"

#######################################
# Premount logging helper.
# Globals:
#   None
# Arguments:
#   *: String to log.
#######################################
log() {
  msg="$*"
  if [ -w /dev/kmsg ]; then
    printf '<6>%s: %s\n' '0024-ciss-crypt-squash' "${msg}" > /dev/kmsg
  else
    printf '%s: %s\n' '0024-ciss-crypt-squash' "${msg}"
  fi
}

### Declare variables ----------------------------------------------------------------------------------------------------------
CDLB_LUKS_FS="/live/ciss_rootfs.crypt"
CDLB_ISO_LABEL="CISS.debian.live"
MNT_MEDIUM="/run/live/medium"
MNT_ROOTFS="/run/live/rootfs"
_PARAMETER=""
_dev=""

for _PARAMETER in ${LIVE_BOOT_CMDLINE}; do

  case "${_PARAMETER}" in

    ciss_crypt_path=*) CDLB_LUKS_FS="${_PARAMETER#ciss_crypt_path=}";;
    ciss_iso_label=* ) CDLB_ISO_LABEL="${_PARAMETER#ciss_iso_label=}";;

  esac

done

mkdir -p "${MNT_MEDIUM}" "${MNT_ROOTFS}"

### Mount the live medium (ISO) read-only, unless already mounted --------------------------------------------------------------
if ! mountpoint -q "${MNT_MEDIUM}"; then

  if [ -n "${CDLB_ISO_LABEL}" ] && [ -e "/dev/disk/by-label/${CDLB_ISO_LABEL}" ]; then

    mount -r -t iso9660 "/dev/disk/by-label/${CDLB_ISO_LABEL}" "${MNT_MEDIUM}" 2>/dev/null \
      || mount -r -t udf "/dev/disk/by-label/${CDLB_ISO_LABEL}" "${MNT_MEDIUM}" 2>/dev/null \
      || log "could not mount label=${CDLB_ISO_LABEL} (iso9660/udf)"

  fi

fi

if ! mountpoint -q "${MNT_MEDIUM}"; then

  ### Fallback scan (covers SR drives and loop-mounted ISOs that udev exposed).
  for _dev in /dev/sr* /dev/cdrom /dev/disk/by-label/*; do

    ### Skip non-block entries early.
    [ -b "${_dev}" ] || continue

    ### Try ISO9660 first, then UDF; only unmount on failure
    if mount -r -t iso9660 "${_dev}" "${MNT_MEDIUM}" 2>/dev/null \
      || mount -r -t udf   "${_dev}" "${MNT_MEDIUM}" 2>/dev/null
    then

      mountpoint -q "${MNT_MEDIUM}" 2>/dev/null && break

    else

      umount "${MNT_MEDIUM}" 2>/dev/null || true

    fi

  done

fi

if ! mountpoint -q "${MNT_MEDIUM}"; then

  log "No live medium mounted, defer to default live-boot path."
  exit 0

fi

### Locate the encrypted root container on the medium. -------------------------------------------------------------------------
if [ ! -f "${MNT_MEDIUM}/${CDLB_LUKS_FS}" ]; then

  log "Encrypted root not found at: [${MNT_MEDIUM}/${CDLB_LUKS_FS}]"
  exit 0

fi

### Create/read FIFO compatible with cryptsetup-initramfs (if present). This allows 'cryptroot-unlock' to feed the passphrase
### over SSH (dropbear).
mkdir -p /lib/cryptsetup
[ -p /lib/cryptsetup/passfifo ] || mkfifo /lib/cryptsetup/passfifo

### Attach a loop device read-only to the encrypted file. ----------------------------------------------------------------------
LOOP="$(losetup -f --show -r "${MNT_MEDIUM}/${CDLB_LUKS_FS}")" || { log "losetup failed"; exit 42; }

### Try to open the LUKS container, first via FIFO (SSH unlock), then interactively. -------------------------------------------
attempts=0
while true; do

  attempts=$((attempts+1))
  echo "Unlock '${CDLB_LUKS_FS}' (try ${attempts}): use 'cryptroot-unlock' over SSH or enter on console" >/dev/console 2>/dev/null || true

  ## Non-blocking read from FIFO (Dropbear and cryptroot-unlock path).
  if timeout 5 cat /lib/cryptsetup/passfifo | cryptsetup open --type luks --readonly "${LOOP}" crypt_liveiso --key-file - 2>/dev/null; then

    break

  fi

  ### Interactive fallback on the console.
  if cryptsetup open --type luks --readonly "${LOOP}" crypt_liveiso; then

    break

  fi

done

### Mount the decrypted payload as SquashFS under '/run/live/rootfs'. ----------------------------------------------------------
mount -r -t squashfs /dev/mapper/crypt_liveiso "${MNT_ROOTFS}" || { log "mount squashfs failed"; exit 1; }

### Ensure live-boot keeps using our medium (bind-mount for consistency). ------------------------------------------------------
mount --bind "${MNT_MEDIUM}" "${MNT_MEDIUM}" 2>/dev/null || true

log "Encrypted squashfs is mounted at: [${MNT_ROOTFS}] (device=/dev/mapper/crypt_liveiso)"

printf "\e[92m[INFO] Successfully applied: [/usr/lib/live/boot/0024-ciss-crypt-squash] \n\e[0m"

exit 0

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