#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-10-11; 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
set -Ceuo pipefail

printf "\e[95m++++ ++++ ++++ ++++ ++++ ++++ ++ 🧪 '%s' starting ... \e[0m\n" "${0}"

[[ -r /root/ciss_xdg_tmp.sh ]] && . /root/ciss_xdg_tmp.sh
export DEBIAN_FRONTEND="noninteractive"
export INITRD="No"

### Declare Arrays, HashMaps, and Variables.
declare var_dropbear_version="2025.88"
declare var_tar="/root/dropbear/dropbear-${var_dropbear_version}.tar.bz2"
declare var_build_dir="/root/build/dropbear-${var_dropbear_version}"
declare var_logfile="/root/.ciss/cdlb/log/0020_dropbear_build.log"

mkdir -p "/root/build"
cp "${var_tar}" "/root/build"
tar xjf "/root/dropbear/dropbear-${var_dropbear_version}.tar.bz2" -C "/root/build"
cp "/root/dropbear/localoptions.h" "${var_build_dir}"
cd "${var_build_dir}"

### Flag Purpose:
#  -fPIE              : Generate position-independent executable code
#  -pie               : Link the executable as PIE (so that ASLR works)
#  -static            : Fully statically linked against musl
#  -s                 : Strip unnecessary symbols directly during linking
#  -Wl,-z,relro,-z,now: Enables full RELRO (symbol resolution at program startup)

# shellcheck disable=SC2016,SC2312
if ! setsid bash -c '
    ### Sterile environment for the build-process.

    export -n SHELLOPTS || true

    set +u

    unset PATH_SEPARATOR
    PATH_SEPARATOR=":"
    PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

    if ! command -v musl-gcc >/dev/null 2>&1; then
      echo "ERROR: musl-gcc not found. Install musl-tools in chroot." >&2
      exit 1
    fi

    CC=musl-gcc \
      CFLAGS="-Os -fPIE -Wno-undef -fstack-protector-strong -D_FORTIFY_SOURCE=2" \
      LDFLAGS="-static -pie -s -Wl,-z,relro,-z,now" \
      ./configure \
      --enable-static \
      --enable-openpty \
      --disable-pam \
      --disable-zlib

    # shellcheck disable=2312
    make -j"$(nproc)"
  ' >| "${var_logfile}" 2>&1
then

  printf "\e[91m++++ ++++ ++++ ++++ ++++ ++++ ++ ❌ Dropbear build failed. See [%s] \e[0m\n" "${var_logfile}" >&2
  tail -n 42 "${var_logfile}" >&2 || true
  exit 42

fi

  rm -rf /root/dropbear

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

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