#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.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: 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.installer
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing

#######################################
# Setup chrony NTPSec client.
# Every 'apt-get install' command is invoked by adding 'export INITRD=No'
# to suppress the 'update-initramfs'-Kernel-Hooks, according to the initramfs-tools manpage:
# https://manpages.debian.org/testing/initramfs-tools-core/initramfs-tools.7.en.html
# Globals:
#   ARY_NTPSRVR
#   DIR_BAK
#   NL
#   TARGET
#   VAR_SETUP_PATH
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
installation_chrony() {
  ### Declare Arrays, HashMaps, and Variables.
  # shellcheck disable=SC2155
  declare     var_of=$(mktemp var_of.XXXXXXXX) var_ntp_server=""
  declare -r  var_logfile="/root/.ciss/cdi/log/4150_installation_chrony.log"

  chroot_logger "${TARGET}${var_logfile}"

  for var_ntp_server in "${ARY_NTPSRVR[@]}"; do

    printf "server %s iburst nts minpoll 5 maxpoll 9 %b" "${var_ntp_server}" "${NL}" >> "${var_of}"

  done

  printf "%b" "${NL}" >> "${var_of}"
  printf "# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh %b" "${NL}" >> "${var_of}"

  mkdir -p "${TARGET}/var/log/chrony"

  do_in_target_script "${TARGET}" "
    export INITRD=No
    apt-get install -y --no-install-recommends --no-install-suggests chrony 2>&1 | tee -a ${var_logfile}
    echo ExitCode: \$? >> ${var_logfile}
  "

  if [[ ! -e "${TARGET}/etc/systemd/system/multi-user.target.wants/chrony.service" ]]; then

    do_in_target_script "${TARGET}" "systemctl enable chrony.service"

  fi

  mkdir -p "${DIR_BAK}/etc/chrony"
  mv "${TARGET}/etc/chrony/chrony.conf" "${DIR_BAK}/etc/chrony/chrony.conf.bak"

  install -D -m 0644 -o root -g root "${VAR_SETUP_PATH}/includes/target/etc/chrony/chrony.cnf" "${TARGET}/etc/chrony/chrony.conf"

  insert_comments "${TARGET}/etc/chrony/chrony.conf"

  cat "${var_of}" >> "${TARGET}/etc/chrony/chrony.conf"

  do_log "debug" "file_only" "4150() Executing: [do_in_target_script ${TARGET} chronyd -Q -f /etc/chrony/chrony.conf]."
  do_in_target_script "${TARGET}" "
    chronyd -Q -f /etc/chrony/chrony.conf 2>&1 | tee -a ${var_logfile}
    echo ExitCode: \$? >> ${var_logfile}
  "

  do_log "info" "file_only" "4150() Chrony NTPsec client installed."

  rm -f "${var_of}"

  guard_dir && return 0
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
