#!/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: 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

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

# Purpose: Copy vendor 'legacy.conf' to '/etc/tmpfiles.d' and drop duplicate '/run/lock' lines.

#######################################
# Simple error terminal logger.
# Arguments:
#   None
#######################################
log() { printf '[tmpfiles-fix] %s\n' "$*" >&2; }

### Locate vendor 'legacy.conf' (The path can vary).
declare vendor=""

for p in /usr/lib/tmpfiles.d/legacy.conf /lib/tmpfiles.d/legacy.conf; do

  if [[ -f "${p}" ]]; then vendor="${p}"; break; fi

done

if [[ -z "${vendor}" ]]; then
  log "WARN: vendor legacy.conf not found; creating a minimal override"
  install -D -m 0644 /dev/null /etc/tmpfiles.d/legacy.conf

else

  install -D -m 0644 "${vendor}" /etc/tmpfiles.d/legacy.conf

fi

### Deduplicate: keep only the FIRST 'd /run/lock ' definition, drop subsequent ones.
# shellcheck disable=SC2155
declare tmpdir="$(mktemp -d)"
declare out="${tmpdir}/legacy.conf"

awk '
BEGIN{seen=0}
{
  # Preserve everything by default
  keep=1
  # Match tmpfiles "d /run/lock ..." (allowing variable spacing and case of directive)
  if ($1 ~ /^[dD]$/ && $2 == "/run/lock") {
    if (seen==1) { keep=0 } else { seen=1 }
  }
  if (keep) print
}' /etc/tmpfiles.d/legacy.conf >| "${out}"

### Install the sanitized file atomically.
install -m 0644 -o root -g root "${out}" /etc/tmpfiles.d/legacy.conf
rm -rf -- "${tmpdir}"

log "Deduplicated /etc/tmpfiles.d/legacy.conf (kept only first /run/lock entry)."

command -v systemd-tmpfiles >/dev/null 2>&1 && systemd-tmpfiles --create --prefix /run/lock || true

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
