#!/usr/bin/env bash
# This script runs inside the ARM root at image build time, never during boot.
set -euo pipefail
trap 'printf "ERROR: rootfs finalization failed at line %s: %s\n" "$LINENO" "$BASH_COMMAND" >&2' ERR
export LC_ALL=C
sed -i 's/^#en_US.UTF-8 UTF-8[[:space:]]*$/en_US.UTF-8 UTF-8/' /etc/default/libc-locales
grep -qx 'en_US.UTF-8 UTF-8' /etc/default/libc-locales
xbps-reconfigure -fa
# Install FDS defaults globally so plain wmaker also uses the grayscale theme.
# Home-directory preferences continue to override these image defaults.
for name in WindowMaker WMRootMenu WMWindowAttributes; do
    install -m644 "/usr/share/fds/eink/$name" "/etc/WindowMaker/$name"
done
# The upstream CA package suppresses updater errors and exits successfully.
# Require the actual generator to succeed instead of trusting that wrapper.
update-ca-certificates --fresh
ldconfig
# This auxiliary cache records build-tree inode identities. Runtime linking uses
# /etc/ld.so.cache; retain that cache and discard only the build-specific index.
rm -f /var/cache/ldconfig/aux-cache
# Repository indexes are build inputs, not installed-package metadata. They
# encode remote URLs or absolute local snapshot paths; preserve the package
# database and keys, and omit only these fetched index directories from SYSTEM.
for repository in /var/db/xbps/*; do
    if [[ -d $repository && -f $repository/aarch64-repodata ]]; then
        rm -rf -- "$repository"
    fi
done
# The exported tar normalizes mtimes to this same epoch. Generate caches against
# those directory timestamps so read-only SYSTEM can use them without rescanning.
: "${SOURCE_DATE_EPOCH:?Missing reproducible image epoch}"
printf '%s\n' "$SOURCE_DATE_EPOCH" >/usr/share/fds/build-epoch
find /usr/share/fonts -type d -exec touch -d "@$SOURCE_DATE_EPOCH" {} +
fc-cache -f
find /usr/share/fonts -type d -exec touch -d "@$SOURCE_DATE_EPOCH" {} +
fc-match Terminus | grep -qi terminus
# Compile with the target s6-rc tools so no host database format is assumed.
s6-rc-compile /etc/s6-rc/compiled /etc/s6-rc/source
s6-linux-init-maker -1 -q 0 -c /etc/s6-linux-init/current \
    -p /usr/bin:/bin -e LANG=en_US.UTF-8 -e TZ=UTC \
    -f /usr/share/fds/init-skel /etc/s6-linux-init/current
for command in init halt poweroff reboot shutdown telinit; do
    test ! -e "/usr/bin/$command"
    ln -s "../../etc/s6-linux-init/current/bin/$command" "/usr/bin/$command"
done
locale -a | grep -qx en_US.utf8
test -s /etc/ld.so.cache
test -s /etc/ssl/certs/ca-certificates.crt
test -s /etc/udev/hwdb.bin
printf 'PASS: ARM package configuration, locales, certificates, hwdb and s6 database\n'
