#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-05-07; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.live.builder.git
# SPDX-FileContributor: ZIMNOL, Andre H.; Private Contributor
# SPDX-FileCopyrightText: 2025; ZIMNOL, Andre H.; <debian@zimnol.eu>
# 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

guard_sourcing

#######################################
# Wrapper for statistic functions of the final build.
# Globals:
#   ERR_UNCRITICAL
#   VAR_BUILD_LOG
#   VAR_CHROOT_DIR
#   VAR_HANDLER_BUILD_DIR
#   VAR_PACKAGES_FILE
# Arguments:
#  None
#######################################
run_analysis() {
  # shellcheck disable=SC2164
  cd "${VAR_HANDLER_BUILD_DIR}"
  # shellcheck disable=SC2155
  declare iso_file=$(find . -maxdepth 1 -name "*.iso" -printf "%f\n" | sort | tail -n1)

  if [[ -z ${iso_file} || ! -f ${iso_file}  ]]; then
    printf "\e[91m❌ No ISO Image found.\e[0m\n" >&2
    exit "${ERR_UNCRITICAL}"
  fi

  printf "\e[92m📊 Start analysis of : %s ... \e[0m\n" "${iso_file}"
  # shellcheck disable=SC2155
  declare iso_size_hr=$(du -h "${iso_file}" | awk '{print $1}')
  # shellcheck disable=SC2155
  declare iso_size_bytes=$(du -b "${iso_file}" | awk '{print $1}')
  # shellcheck disable=SC2155
  declare chroot_size_hr=$(du -sh "${VAR_CHROOT_DIR}" 2> /dev/null | awk '{print $1}')
  # shellcheck disable=SC2155
  declare chroot_size_bytes=$(du -sb "${VAR_CHROOT_DIR}" 2> /dev/null | awk '{print $1}')
  # shellcheck disable=SC2155
  declare compression=$(awk -v iso="${iso_size_bytes}" -v chroot="${chroot_size_bytes}" 'BEGIN { printf "%.2f%%", 100 * iso / chroot }')
  # shellcheck disable=SC2155
  declare package_count=$(wc -l < "${VAR_PACKAGES_FILE}" 2> /dev/null || echo "nicht gefunden")
  # shellcheck disable=SC2155
  declare squash_cpu_used="$(grep -m1 -oP 'Using \K[0-9]+' "${VAR_BUILD_LOG}")"

  if [[ -f "${VAR_BUILD_LOG}" ]]; then
    # shellcheck disable=SC2155
    declare start_line=$(grep 'lb build' "${VAR_BUILD_LOG}" | head -n1 || true)
    # shellcheck disable=SC2155
    declare end_line=$(grep 'lb source' "${VAR_BUILD_LOG}" | tail -n1 || true)

    if [[ -n "${start_line}" && -n "${end_line}" ]]; then
      # shellcheck disable=SC2155
      declare start_epoch=$(echo "${start_line}" | sed -E 's/^\[([0-9:-]+ [0-9:]+)\].*/\1/' | xargs -I{} date -d "{}" +%s)
      # shellcheck disable=SC2155
      declare end_epoch=$(echo "${end_line}" | sed -E 's/^\[([0-9:-]+ [0-9:]+)\].*/\1/' | xargs -I{} date -d "{}" +%s)
      # shellcheck disable=SC2155
      declare duration_sec=$((end_epoch - start_epoch))
      # shellcheck disable=SC2155
      declare duration_min=$((duration_sec / 60))
      # shellcheck disable=SC2155
      declare duration_rest=$((duration_sec % 60))
      # shellcheck disable=SC2155
      declare build_duration=$(printf "%02dm:%02ds" "${duration_min}" "${duration_rest}")
    else
      declare build_duration="(Timestamp not found)"
    fi
  else
    declare build_duration="(No log file found)"
  fi

  # shellcheck disable=SC2155
  declare sha_sum=$(sha256sum "$iso_file" | tee "$iso_file.sha256" | awk '{print $1}')
  # shellcheck disable=SC2155
  declare time=$(date '+%Y-%m-%d %H:%M:%S')

  printf "\e[92m🧾 === Build summary === \e[0m\n"
  printf "\e[92m----------------------------------------------------------------------------------------\e[0m\n"
  printf "\e[97m📦 ISO-File          : %s \e[0m\n" "${iso_file}"
  printf "\e[97m📀 ISO-Size          : %s \e[0m\n" "${iso_size_hr}"
  printf "\e[97m📂 Chroot-Size       : %s \e[0m\n" "${chroot_size_hr}"
  printf "\e[97m📉 Compression-level : %s \e[0m\n" "${compression}"
  printf "\e[97m📦 Packages          : %s \e[0m\n" "${package_count}"
  printf "\e[97m🕐 Build Time        : %s \e[0m\n" "${build_duration}"
  printf "\e[97m🧠 CPUs for SquashFS : %s \e[0m\n" "${squash_cpu_used}"
  printf "\e[97m🔐 SHA256SUM         : %s \e[0m\n" "${sha_sum}"
  printf "\e[92m----------------------------------------------------------------------------------------\e[0m\n"
  printf "\e[97m📅 Analysis Time     : %s \e[0m\n" "${time}"
  printf "\e[92m✅ Analysis completed.\e[0m\n"
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
