#!/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: GPL-3.0-or-later
# 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

### Modified Version of the original file:
### https://salsa.debian.org/live-team/live-boot 'components/9990-main.sh'
### Change the behavior so that the ciss_rootfs.crypt (0024-ciss-crypt-squash) is mounted when it is opened.

# set -e

printf "\e[95m[INFO] Sourcing             : [/usr/lib/live/boot/9990-main.sh] \n\e[0m"

Live ()
{
  printf "\e[95m[INFO] Starting             : [/usr/lib/live/boot/9990-main.sh] \n\e[0m"

  if [ -x /scripts/local-top/cryptroot ]
  then
    /scripts/local-top/cryptroot
  fi

  exec 6>&1
  exec 7>&2
  exec > boot.log
  exec 2>&1
  tail -f boot.log >&7 &
  tailpid="${!}"

  # shellcheck disable=SC2034
  LIVE_BOOT_CMDLINE="${LIVE_BOOT_CMDLINE:-$(cat /proc/cmdline)}"
  Cmdline_old

  Debug

  Read_only

  Select_eth_device

  if [ -e /conf/param.conf ]
  then
    . /conf/param.conf
  fi

  # Needed here too because some things (*cough* udev *cough*)
  # change the timeout

  if [ -n "${NETBOOT}" ] || [ -n "${FETCH}" ] || [ -n "${HTTPFS}" ] || [ -n "${FTPFS}" ]
  then
    if do_netmount
    then
      livefs_root="${mountpoint?}"
    else
      panic "Unable to find a live file system on the network"
    fi
  else
    if [ -n "${ISCSI_PORTAL}" ]
    then
      do_iscsi && livefs_root="${mountpoint}"
    elif [ -n "${PLAIN_ROOT}" ] && [ -n "${ROOT}" ]
    then
      # Do a local boot from hd
      livefs_root=${ROOT}
    else
      Setup_Memdisk

      # If the live media location is given via command line and access to it
      # involves LVM volumes, the corresponding volumes need to be activated.
      IFS=','
      # shellcheck disable=SC2116
      for dev in $(echo "${LIVE_MEDIA}")
      do
        case "${dev}" in
          /dev/mapper/*)
            # shellcheck disable=SC2046,SC2312
            eval $(dmsetup splitname --nameprefixes --noheadings --rows "${dev#/dev/mapper/}")
            # shellcheck disable=SC2244
            if [ "${DM_VG_NAME}" ] && [ "${DM_LV_NAME}" ]
            then
              lvm lvchange -aay -y --sysinit --ignoreskippedcluster "${DM_VG_NAME}/${DM_LV_NAME}"
            fi
            ;;
          /dev/*/*)
          # Could be /dev/VG/LV; use lvs to check
            if lvm lvs -- "${dev}" >/dev/null 2>&1
            then
              lvm lvchange -aay -y --sysinit --ignoreskippedcluster "${dev}"
            fi
            ;;
        esac
      done
      unset IFS

      ### Skip autodetection, '$livefs_root' was pre-seeded by '0024-ciss-crypt-squash'. ---------------------------------------
      if [ -n "${livefs_root:-}" ]; then

        printf "\e[92m[INFO] live()               : Using preseeded [livefs_root=%s] skipping autodetect. \e[0m\n" "${livefs_root}"

      else

        ### Scan local devices for the image.
        i=0
        while [ "${i}" -lt 60 ]; do

          # shellcheck disable=SC2086
          livefs_root=$(find_livefs ${i})

          if [ -n "${livefs_root}" ]; then
            break
          fi

          sleep 1
          i=$((i + 1))

        done

      fi

    fi

  fi

  printf "\e[93m[DEBUG] live(): [%s] -> livefs_root. \e[0m\n" "${livefs_root}"
  if [ -z "${livefs_root}" ]; then

    printf "\e[91m[FATAL] live()              : Unable to find a medium containing a live file system. \e[0m\n"
    sleep 60
    log   "[FATAL] live()              : Unable to find a medium containing a live file system."
    panic "[FATAL] live()              : Unable to find a medium containing a live file system."

  fi

  Verify_checksums "${livefs_root}"

  # shellcheck disable=SC2244
  if [ "${TORAM}" ]; then

    live_dest="ram"

  elif [ "${TODISK}" ]; then

    live_dest="${TODISK}"

  fi

  # shellcheck disable=SC2244
  if [ "${live_dest}" ]; then

    log_begin_msg "Copying live media to ${live_dest}"
    copy_live_to "${livefs_root}" "${live_dest}"
    log_end_msg

  fi

  # if we do not unmount the ISO, we can't run "fsck /dev/ice" later on
  # because the mountpoint is left behind in /proc/mounts, so let's get
  # rid of it when running from RAM
  # shellcheck disable=SC2244
  if [ -n "${FROMISO}" ] && [ "${TORAM}" ]; then

    losetup -d /dev/loop0

    if is_mountpoint /run/live/fromiso; then

      umount /run/live/fromiso
      rmdir --ignore-fail-on-non-empty /run/live/fromiso >/dev/null 2>&1 || true

    fi

  fi

  if [ -n "${MODULETORAMFILE}" ] || [ -n "${PLAIN_ROOT}" ]
  then
    printf "\e[92m[INFO] Live()               : [setup_unionfs livefs_root=%s rootmnt=%s] \e[0m\n" "${livefs_root}" "${rootmnt?}"
    setup_unionfs "${livefs_root}" "${rootmnt?}"
  else
    mac="$(get_mac)"
    mac="$(echo "${mac}" | sed 's/-//g')"
    printf "\e[92m[INFO] Live()               : [mount_images_in_directory livefs_root=%s rootmnt=%s mac=%s] \e[0m\n" "${livefs_root}" "${rootmnt}" "${mac}"
    mount_images_in_directory "${livefs_root}" "${rootmnt}" "${mac}"
  fi

  if [ -n "${ROOT_PID}" ]
  then
    echo "${ROOT_PID}" > "${rootmnt}"/lib/live/root.pid
  fi

  log_end_msg

  # aufs2 in kernel versions around 2.6.33 has a regression:
  # directories can't be accessed when read for the first time,
  # causing a failure, for example, when accessing /var/lib/fai
  # when booting FAI, this simple workaround solves it
  ls /root/* >/dev/null 2>&1

  # if we do not unmount the ISO, we can't run "fsck /dev/ice" later on
  # because the mountpoint is left behind in /proc/mounts, so let's get
  # rid of it when running from RAM
  # shellcheck disable=SC2244
  if [ -n "${FINDISO}" ] && [ "${TORAM}" ]
  then
    losetup -d /dev/loop0

    if is_mountpoint /run/live/findiso
    then
      umount /run/live/findiso
      rmdir --ignore-fail-on-non-empty /run/live/findiso \
        >/dev/null 2>&1 || true
    fi
  fi

  if [ -f /etc/hostname ] && ! grep -E -q -v '^[[:space:]]*(#|$)' "${rootmnt}/etc/hostname"
  then
    log_begin_msg "Copying /etc/hostname to ${rootmnt}/etc/hostname"
    cp -v /etc/hostname "${rootmnt}/etc/hostname"
    log_end_msg
  fi

  if [ -f /etc/hosts ] && ! grep -E -q -v '^[[:space:]]*(#|$|(127.0.0.1|::1|ff02::[12])[[:space:]])' "${rootmnt}/etc/hosts"
  then
    log_begin_msg "Copying /etc/hosts to ${rootmnt}/etc/hosts"
    cp -v /etc/hosts "${rootmnt}/etc/hosts"
    log_end_msg
  fi

  ### CISS override for systemd-networkd stack ---------------------------------------------------------------------------------
  #if [ -L /root/etc/resolv.conf ] ; then
  #  # assume we have resolvconf
  #  DNSFILE="${rootmnt}/etc/resolvconf/resolv.conf.d/base"
  #else
  #  DNSFILE="${rootmnt}/etc/resolv.conf"
  #fi
  #if [ -f /etc/resolv.conf ] && ! grep -E -q -v '^[[:space:]]*(#|$)' "${DNSFILE}"
  #then
  #  log_begin_msg "Copying /etc/resolv.conf to ${DNSFILE}"
  #  cp -v /etc/resolv.conf "${DNSFILE}"
  #  log_end_msg
  #fi
  ### CISS override for systemd-networkd stack ---------------------------------------------------------------------------------

  if ! [ -d "/lib/live/boot" ]
  then
    panic "A wrong rootfs was mounted."
  fi

  Fstab
  Netbase

  Swap

  exec 1>&6 6>&-
  exec 2>&7 7>&-
  kill "${tailpid}"
  [ -w "${rootmnt}/var/log/" ] && mkdir -p "${rootmnt}/var/log/live" && ( \
    cp boot.log "${rootmnt}/var/log/live" 2>/dev/null; \
    cp fsck.log "${rootmnt}/var/log/live" 2>/dev/null )

  sleep 3

  printf "\e[92m[INFO] Successfully applied : [/usr/lib/live/boot/9990-main.sh] \n\e[0m"
}
