#!/usr/bin/env bash
# Converge the root config that is safe to reconcile continuously, on every pass,
# with no reboot: the declared sysctl and journald drop-ins, plus the commands that
# activate them.
#
# Its counterpart apply.sh is a PROVISIONING step — it also partitions and formats
# the scratch disk, rewrites sshd's listen policy and re-arms the hardware watchdog,
# so it is gated behind `buildbox harden` and a reboot. Bundling the two made a
# two-second sysctl fix cost a reboot nobody authorizes, which is why kernel.panic
# and the journal cap sat drifted for a week. Convergence is continuous;
# provisioning is one-time and gated. This file is the continuous half.
#
# The safe set is an ALLOWLIST, never "apply.sh minus the scary parts": a new
# destructive step added to apply.sh must never silently join this path. A sshd
# listen change once stranded debian2 with no rescue door, so sshd is out too.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DRY_RUN="${CONVERGE_SAFE_DRY_RUN:-0}"
SYSCTL_DIR="${CONVERGE_SAFE_SYSCTL_DIR:-/etc/sysctl.d}"
JOURNALD_DIR="${CONVERGE_SAFE_JOURNALD_DIR:-/etc/systemd/journald.conf.d}"

changed_sysctl=0
changed_journald=0

install_declared() { # source-subdir target-dir -> echoes CHANGED when a file was written
  local src="$HERE/$1" dst="$2" f rel target
  [ -d "$src" ] || return 0
  while IFS= read -r -d '' f; do
    rel="${f#"$src"/}"
    target="$dst/$rel"
    if [ -f "$target" ] && cmp -s "$f" "$target"; then
      printf 'OK    %s\n' "$target"
      continue
    fi
    if [ "$DRY_RUN" = 1 ]; then
      printf 'WOULD %s\n' "$target"
    else
      install -D -m 0644 -o root -g root "$f" "$target"
      printf 'WROTE %s\n' "$target"
    fi
    echo CHANGED
  done < <(find "$src" -type f -print0 | sort -z)
}

while IFS= read -r line; do
  [ "$line" = CHANGED ] && { changed_sysctl=1; continue; }
  printf '%s\n' "$line"
done < <(install_declared sysctl.d "$SYSCTL_DIR")

while IFS= read -r line; do
  [ "$line" = CHANGED ] && { changed_journald=1; continue; }
  printf '%s\n' "$line"
done < <(install_declared journald.conf.d "$JOURNALD_DIR")

if [ "$DRY_RUN" = 1 ]; then
  printf 'converge-safe dry-run sysctl_changed=%s journald_changed=%s\n' "$changed_sysctl" "$changed_journald"
  exit 0
fi

# Activation is unconditional for sysctl (cheap, idempotent, and it also repairs a
# value someone set by hand at runtime) and conditional for journald, whose restart
# briefly interrupts logging.
sysctl --system >/dev/null
printf 'ACTIVATED sysctl\n'

if [ "$changed_journald" = 1 ]; then
  systemctl restart systemd-journald.service
  printf 'ACTIVATED systemd-journald\n'
fi
