#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-05-05; 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: LicenseRef-CNCL-1.1 OR LicenseRef-CCLA-1.1
# 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

guard_sourcing || return "${ERR_GUARD_SRCE}"

#######################################
# Module to update '/usr/lib/live/build/...' scripts.
# Globals:
#   BASH_SOURCE
#   VAR_WORKDIR
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
ciss_upgrades_build() {
  printf "\e[95m++++ ++++ ++++ ++++ ++++ ++++ ++ 🧪 %s starting ... \e[0m\n" "${BASH_SOURCE[0]}"

  ### CISS 0030-ciss-verify-checksums override. --------------------------------------------------------------------------------
  if [[ -e /usr/lib/live/boot/0030-verify-checksums ]]; then

    mkdir -p /usr/lib/live/backup

    if [[ -e /usr/lib/live/backup/0030-verify-checksums.original ]]; then

      rm -f /usr/lib/live/boot/0030-verify-checksums

    else

      mv /usr/lib/live/boot/0030-verify-checksums /usr/lib/live/backup/0030-verify-checksums.original

    fi

  fi

  ### CISS signing binary-checksums override. ----------------------------------------------------------------------------------
  if [[ ! -e /usr/lib/live/build/binary_checksums.original ]]; then

    cp /usr/lib/live/build/binary_checksums /usr/lib/live/build/binary_checksums.original
    chmod 0444 /usr/lib/live/build/binary_checksums.original

  fi

  rm -f /usr/lib/live/build/binary_checksums
  install -m 0755 -o root -g root "${VAR_WORKDIR}/scripts/usr/lib/live/build/binary_checksums.sh" /usr/lib/live/build/binary_checksums

  ### https://wiki.debian.org/ReproducibleInstalls/LiveImages
  ### https://reproducible-builds.org/docs/system-images/
  ### https://gitlab.tails.boum.org/tails/tails/-/blob/stable/config/chroot_local-includes/usr/share/tails/build/mksquashfs-excludes
  if [[ ! -e /usr/lib/live/build/binary_rootfs.original ]]; then

    cp /usr/lib/live/build/binary_rootfs /usr/lib/live/build/binary_rootfs.original
    chmod 0444 /usr/lib/live/build/binary_rootfs.original

  fi

  rm -f /usr/lib/live/build/binary_rootfs
  install -m 0755 -o root -g root "${VAR_WORKDIR}/scripts/usr/lib/live/build/binary_rootfs.sh" /usr/lib/live/build/binary_rootfs

  printf "\e[92m++++ ++++ ++++ ++++ ++++ ++++ ++ ✅ %s successfully applied. \e[0m\n" "${BASH_SOURCE[0]}"

  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f ciss_upgrades_build
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
