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

# 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

# No bash in the installer environment, only BusyBox.

set -o errexit
set -o nounset
set -o noclobber

export PATH="${PATH}:/sbin:/usr/sbin:/.ciss/install:/.ciss/install/.ash"
. /.ciss/install/.ash/di_scripting_flexibility.sh

readonly DISK_NAME="sda"
readonly DISK_PATH="/dev/${DISK_NAME}"
readonly SLEEPTIMER="2"

do_sleep() {
  sleep "${SLEEPTIMER}"
}

modprobe btrfs || true
modprobe ext4 || true

blkdiscard "${DISK_PATH}"
parted "${DISK_PATH}" --script -- mklabel gpt

#/dev/sda1 -- ESP
do_dev_sda1() {
  parted "${DISK_PATH}" --script -- mkpart ESP fat32 1MiB 512MiB set 1 esp on
  do_sleep

  FORMAT_LABEL="ESP"
  PARTITION="${DISK_PATH}1"

  format_partition() {
    if mkfs.fat -F32 -n "${FORMAT_LABEL}" "${PARTITION}"; then
      echo "Partition: ${PARTITION} successfully formatted with FAT32."
    else
      echo "Partition: ${PARTITION} NOT successfully formated with FAT32."
    fi

    if blkid "${PARTITION}" | grep -q 'TYPE="vfat"'; then
      echo "Partition: ${PARTITION} correctly formatted with FAT32."
    else
      echo "Partition: ${PARTITION} NOT correctly formatted with FAT32."
    fi
  }

  ATTEMPTS=0
  MAX_ATTEMPTS=3
  while ! format_partition && [ ${ATTEMPTS} -lt ${MAX_ATTEMPTS} ]; do
    echo "Repeat formatting... attempt $((ATTEMPTS + 1))"
    ATTEMPTS=$((ATTEMPTS + 1))
  done

  if [ ${ATTEMPTS} -ge ${MAX_ATTEMPTS} ]; then
    echo "Error: Partition ${PARTITION} could not be formatted correctly after ${MAX_ATTEMPTS} attempts."
  else
    echo "Partition ${PARTITION} successfully formatted and checked."
  fi
}
do_dev_sda1

#/dev/sda2 -- /boot
do_dev_sda2() {
  parted "${DISK_PATH}" --script -- mkpart primary ext4 512MiB 4096MiB
  do_sleep

  FORMAT_LABEL="boot"
  PARTITION="${DISK_PATH}2"

  format_partition() {
    if mkfs.ext4 -L "${FORMAT_LABEL}" "${PARTITION}"; then
      echo "Partition: ${PARTITION} successfully formatted with ext4."
    else
      echo "Partition: ${PARTITION} NOT successfully formated with ext4."
    fi

    if blkid "${PARTITION}" | grep -q 'TYPE="ext4"'; then
      echo "Partition: ${PARTITION} correctly formatted with ext4."
    else
      echo "Partition: ${PARTITION} NOT correctly formatted with ext4."
    fi
  }

  ATTEMPTS=0
  MAX_ATTEMPTS=3
  while ! format_partition && [ ${ATTEMPTS} -lt ${MAX_ATTEMPTS} ]; do
    echo "Repeat formatting... attempt $((ATTEMPTS + 1))"
    ATTEMPTS=$((ATTEMPTS + 1))
  done

  if [ ${ATTEMPTS} -ge ${MAX_ATTEMPTS} ]; then
    echo "Error: Partition ${PARTITION} could not be formatted correctly after ${MAX_ATTEMPTS} attempts."
  else
    echo "Partition ${PARTITION} successfully formatted and checked."
  fi
}
do_dev_sda2

#/dev/sda3 -- preparing for crypt_ephemeral_swap
parted "${DISK_PATH}" --script -- mkpart primary 4096MiB 8192MiB
do_sleep

#/dev/sda4 -- preparing for crypt_ephemeral_tmp
parted "${DISK_PATH}" --script -- mkpart primary 8192MiB 12288MiB
do_sleep

#/dev/sda5 -- /home
parted "${DISK_PATH}" --script -- mkpart primary 12288MiB 45056MiB
do_sleep

#/dev/sda6 -- /
parted "${DISK_PATH}" --script -- mkpart primary 45056MiB 77824MiB
do_sleep

#/dev/sda7 -- /usr
parted "${DISK_PATH}" --script -- mkpart primary 77824MiB 143360MiB
do_sleep

#/dev/sda8 -- /var
parted "${DISK_PATH}" --script -- mkpart primary 143360MiB 208896MiB
do_sleep

#/dev/sda9 -- /var/log
parted "${DISK_PATH}" --script -- mkpart primary 208896MiB 225280MiB
do_sleep

#/dev/sda10 -- /var/log/audit
parted "${DISK_PATH}" --script -- mkpart primary 225280MiB 241664MiB
do_sleep

#/dev/sda11 -- /var/tmp
parted "${DISK_PATH}" --script -- mkpart primary 241664MiB 258048MiB
do_sleep

#/dev/sda12 -- temporary installation /tmp
do_dev_sda12() {
  parted "${DISK_PATH}" --script -- mkpart primary 258048MiB 261120MiB
  do_sleep

  FORMAT_LABEL="installation_tmp"
  PARTITION="${DISK_PATH}12"

  format_partition() {
    if mkfs.ext4 -L "${FORMAT_LABEL}" "${PARTITION}"; then
      echo "Partition: ${PARTITION} successfully formatted with ext4."
    else
      echo "Partition: ${PARTITION} NOT successfully formated with ext4."
    fi

    if blkid "${PARTITION}" | grep -q 'TYPE="ext4"'; then
      echo "Partition: ${PARTITION} correctly formatted with ext4."
    else
      echo "Partition: ${PARTITION} NOT correctly formatted with ext4."
    fi
  }

  ATTEMPTS=0
  MAX_ATTEMPTS=3
  while ! format_partition && [ ${ATTEMPTS} -lt ${MAX_ATTEMPTS} ]; do
    echo "Repeat formatting... attempt $((ATTEMPTS + 1))"
    ATTEMPTS=$((ATTEMPTS + 1))
  done

  if [ ${ATTEMPTS} -ge ${MAX_ATTEMPTS} ]; then
    echo "Error: Partition ${PARTITION} could not be formatted correctly after ${MAX_ATTEMPTS} attempts."
  else
    echo "Partition ${PARTITION} successfully formatted and checked."
  fi
}
do_dev_sda12

# Encrypt and open /dev/sda5 to /dev/sda11
i=5
while [ "${i}" -lt 12 ]; do
  PARTITION="/dev/${DISK_NAME}${i}"
  MAPPER_NAME="crypt_${DISK_NAME}${i}"

  if cryptsetup luksFormat "${PARTITION}" --key-file=/.ciss/install/.cfg/.password.cfg --batch-mode --type luks2 --cipher aes-xts-plain64 --key-size 512 --hash sha512 --iter-time 3000 --use-random --verbose; then
    echo  "Partition: ${PARTITION} successfully encrypted."
    do_sleep

    if cryptsetup open "${PARTITION}" "${MAPPER_NAME}" --key-file=/.ciss/install/.cfg/.password.cfg; then
      echo  "Partition: ${PARTITION} successfully opened as: ${MAPPER_NAME}."

      if mkfs.btrfs -L "${MAPPER_NAME}" /dev/mapper/"${MAPPER_NAME}"; then
        echo  "Partition: ${PARTITION} successfully formatted."
      else
        echo  "Partition: ${PARTITION} NOT successfully formatted."
      fi

    else
      echo  "Partition: ${PARTITION} NOT successfully opened as: ${MAPPER_NAME}."
    fi

  else
    echo  "Partition: ${PARTITION} NOT successfully encrypted."
  fi

  i=$((i + 1))
done

do_sleep

# Generate /target directories-
FILE_DIR="/.ciss/install/.cfg/.directories.cfg"

# Check that the file exists.
if [ ! -f "${FILE_DIR}" ]; then
  echo "Error: File ${FILE_DIR} cannot be read." >&2
  exit 1
fi

while read -r DIR; do
  sleep 1
  # Proceed only if the row is not empty.
  if [ -n "${DIR}" ]; then
    # Verify if the directory already exists.
    if [ -d "${DIR}" ]; then
      echo "Directory ${DIR} already exists."
    else
      # Try to create a directory.
      until [ -d "${DIR}" ]; do
        mkdir -p "${DIR}"
        if [ ! -d "${DIR}" ]; then
          echo "Error: Creating ${DIR} directory failed. Try again. " >&2
          sleep 1
        fi
      done
      echo "Directory ${DIR} created successfully".
    fi
  fi
done < "${FILE_DIR}"

do_sleep

mount /dev/mapper/crypt_sda6 /target
do_sleep

mkdir /target/boot
mount /dev/sda2 /target/boot
do_sleep

mkdir /target/boot/efi
mount /dev/sda1 /target/boot/efi
do_sleep

mkdir /target/home
mount /dev/mapper/crypt_sda5 /target/home
do_sleep

mkdir /target/usr
mount /dev/mapper/crypt_sda7 /target/usr
do_sleep

mkdir /target/var
mount /dev/mapper/crypt_sda8 /target/var
do_sleep

mkdir /target/var/log
mount /dev/mapper/crypt_sda9 /target/var/log
do_sleep

mkdir /target/var/log/audit
mount /dev/mapper/crypt_sda10 /target/var/log/audit
do_sleep

mkdir /target/var/tmp
mount /dev/mapper/crypt_sda11 /target/var/tmp
do_sleep

mkdir /target/tmp
mount /dev/sda12 /target/tmp
do_sleep

mkdir /target/dev
mount --bind /dev /target/dev
do_sleep
if [ -d "/target/dev/pts" ]; then
  echo "Directory /target/dev/pts already exists."
else
  mkdir /target/dev/pts
fi

mkdir /target/proc
mount --bind /proc /target/proc
do_sleep

mkdir /target/sys
mount --bind /sys /target/sys
do_sleep

mkdir /target/run
mount --bind /run /target/run
do_sleep
if [ -d "/target/run/lock" ]; then
  echo "Directory /target/run/lock already exists."
else
  mkdir /target/run/lock
fi

mkdir /target/etc
mkdir /target/etc/apt
mkdir /target/etc/network
touch /target/etc/fstab
chmod 0644 /target/etc/fstab

# shellcheck disable=SC2129
cat << EOF >> /target/etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# systemd generates mount units based on this file, see systemd.mount(5).
# Please run 'systemctl daemon-reload' after making changes here.
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>

EOF

echo "# / was on /dev/mapper/crypt_sda6 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda6) / btrfs defaults,errors=remount-ro 0 1" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /boot was on /dev/sda2 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/sda2) /boot ext4 defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /boot/efi was on /dev/sda1 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/sda1) /boot/efi vfat umask=0077 0 1" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /home was on /dev/mapper/crypt_sda5 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda5) /home btrfs defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /usr was on /dev/mapper/crypt_sda7 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda7) /usr btrfs defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /var was on /dev/mapper/crypt_sda8 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda8) /var btrfs defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /var/log was on /dev/mapper/crypt_sda9 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda9) /var/log btrfs defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /var/log/audit was on /dev/mapper/crypt_sda10 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda10) /var/log/audit btrfs defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /var/tmp was on /dev/mapper/crypt_sda11 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda11) /var/tmp btrfs defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /tmp was on /dev/sda12 during installation" >> /target/etc/fstab
echo "UUID=$(blkid -s UUID -o value /dev/sda12) /tmp ext4 defaults 0 2" >> /target/etc/fstab
echo "" >> /target/etc/fstab

echo "# /media/cdrom0 was on /dev/sr0 during installation" >> /target/etc/fstab
echo "/dev/sr0        /media/cdrom0   udf,iso9660 user,noauto     0       0" >> /target/etc/fstab
echo "" >> /target/etc/fstab

touch /target/etc/crypttab
chmod 0644 /target/etc/crypttab

# shellcheck disable=SC2129
cat << EOF >> /target/etc/crypttab
# <name>  <device>  <password-file-or-none>  <options>

EOF

echo "# / was on /dev/mapper/crypt_sda6 during installation" >> /target/etc/crypttab
echo "crypt_sda6 UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda6) none luks,discard" >> /target/etc/crypttab
echo "" >> /target/etc/crypttab

echo "# /home was on /dev/mapper/crypt_sda5 during installation" >> /target/etc/crypttab
echo "crypt_sda5 UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda5) none luks,discard" >> /target/etc/crypttab
echo "" >> /target/etc/crypttab

echo "# /usr was on /dev/mapper/crypt_sda7 during installation" >> /target/etc/crypttab
echo "crypt_sda7 UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda7) none luks,discard" >> /target/etc/crypttab
echo "" >> /target/etc/crypttab

echo "# /var was on /dev/mapper/crypt_sda8 during installation" >> /target/etc/crypttab
echo "crypt_sda8 UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda8) none luks,discard" >> /target/etc/crypttab
echo "" >> /target/etc/crypttab

echo "# /var/log was on /dev/mapper/crypt_sda9 during installation" >> /target/etc/crypttab
echo "crypt_sda9 UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda9) none luks,discard" >> /target/etc/crypttab
echo "" >> /target/etc/crypttab

echo "# /var/log/audit was on /dev/mapper/crypt_sda10 during installation" >> /target/etc/crypttab
echo "crypt_sda10 UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda10) none luks,discard" >> /target/etc/crypttab
echo "" >> /target/etc/crypttab

echo "# /var/tmp was on /dev/mapper/crypt_sda11 during installation" >> /target/etc/crypttab
echo "crypt_sda11 UUID=$(blkid -s UUID -o value /dev/mapper/crypt_sda11) none luks,discard" >> /target/etc/crypttab
echo "" >> /target/etc/crypttab

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