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

set -Ceuo pipefail
umask 0077

declare -grx  VAR_SEMAPHORE="/root/cdi.ciss" # Semaphore to appear.
declare -girx VAR_TIMEOUT=3600               # Semaphore timer in seconds.

install -d -m 0755 /run/lock
exec 9> /run/lock/9999_cdi_starter.lock
flock -n 9 || { echo "9999_cdi_starter already running. Exiting."; exit 0; }

#######################################
# Call into the CISS.debian.installer once the semaphore file is present.
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
cdi() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -i rc=""

  ./ciss_debian_installer.sh \
    --autoinstall \
    --debug XTRACE \
    --log debug \
    --reionice-priority 1 0 \
    --renice-priority "-19" \

  rc="$?"

  if [[ "${rc}" -eq 0 ]]; then

    ### In autoinstall mode this command should never be reached due to the reboot command inside ciss_debian_installer.sh.
    logger -t cdi-watcher "cdi(): ciss_debian_installer.sh completed SUCCESSFULLY [${rc}]."
    exit 0

  else

    logger -t cdi-watcher "cdi(): ciss_debian_installer.sh FAILED [${rc}]."
    exit "${rc}"

  fi
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f cdi

#######################################
# Wait for network connectivity by looping.
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
net_wait() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -i i=1

  for i in {1..60}; do

    getent hosts git.coresecret.dev >/dev/null && break
    sleep 1

  done

  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f net_wait

#######################################
# Wrapper for loading CISS hardened Kernel Parameters.
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
sysp() {
  sysctl -p /etc/sysctl.d/99_local.hardened

  # shellcheck disable=SC2312
  sysctl -a | grep -E 'kernel|vm|net' >| /var/log/sysctl_check"$(date +"%Y-%m-%d_%H:%M:%S")".log

  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f sysp

#######################################
# Main autostart function.
# Arguments:
#   None
#######################################
main() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -r  var_repo_url="https://git.coresecret.dev/msw/CISS.debian.installer.git"
  declare -r  var_repo_dir="/root/git/CISS.debian.installer"
  declare -i  i=""
  declare     var_log="" var_mode=""

  ### Prepare logging.
  install -d -m 0700 /root/.ciss/cdi
  install -d -m 0700 /root/.ciss/cdi/log
  var_log="/root/.ciss/cdi/log/9999-cdi-starter_$(date +"%Y-%m-%d_%H-%M-%S").log"
  touch "${var_log}"

  # shellcheck disable=SC2312
  exec > >(tee -a "${var_log}") 2>&1

  printf "CISS.debian.installer Master V8.13.408.2025.11.13 is up! \n" >> "${var_log}"

  ### Sleep a moment to settle boot artifacts.
  sleep 8

  ### Harden Kernel parameters.
  printf "Command: [sysp] to be executed ... \n" >> "${var_log}"
  sysp
  printf "Command: [sysp] executed.\n" >> "${var_log}"

  ### Wait for network connectivity.
  printf "Command: [net_wait] to be executed ... \n" >> "${var_log}"
  net_wait
  printf "Command: [net_wait] executed.\n" >> "${var_log}"

  ### apt update.
  apt-get update >> "${var_log}"

  ### Download CISS.debian.installer.
  cd /root/git
  [[ -d "${var_repo_dir}" ]] && rm -rf "${var_repo_dir}"
  git clone "${var_repo_url}" "${var_repo_dir}"
  chmod 0700 "${var_repo_dir}/ciss_debian_installer.sh"
  cd "${var_repo_dir}"
  printf "Command: [git clone %s %s] executed.\n" "${var_repo_url}" "${var_repo_dir}" >> "${var_log}"

  ### Poll up to VAR_TIMEOUT seconds for the semaphore to appear and be mode 0600.
  for ((i=0; i<VAR_TIMEOUT; i++)); do

    if [[ -e "${VAR_SEMAPHORE}" && ! -s "${VAR_SEMAPHORE}" ]]; then

      var_mode="$(stat -c '%a' -- "${VAR_SEMAPHORE}" 2>/dev/null || echo '?')"

      if [[ "${var_mode}" == "600" ]]; then

        logger -t cdi-watcher "Semaphore found (${VAR_SEMAPHORE}, mode 0600) after ${i}s -> invoking cdi()"
        printf "Command: [cdi] to be executed.\n" >> "${var_log}"

        cdi
        ### cdi() never returns (it exits the script), so no code below this point in the 'then'-block will run.

      else

        logger -t cdi-watcher "Semaphore ${VAR_SEMAPHORE} present but wrong mode ${var_mode} (expected 600); ignoring"
        printf "INFO: [Semaphore %s present but wrong mode %s (expected 600); ignoring] executed.\n" "${VAR_SEMAPHORE}}" "${var_mode}}" >> "${var_log}"

      fi

    fi

    sleep 1

  done

  ### Timeout reached without acceptable semaphore.
  logger -t cdi-watcher "No valid semaphore ${VAR_SEMAPHORE} (mode 0600) within ${VAR_TIMEOUT}s; exiting idle."
  printf "CISS.debian.installer Master V8.13.408.2025.11.13: No valid semaphore [%s] within [%s]s.\n" "${VAR_SEMAPHORE}" "${VAR_TIMEOUT}" >> "${var_log}"

  exit 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f main

main "$@"

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