#!/bin/sh
# Register the identity shim in /etc/ld.so.preload (NAROS.md §2.3).
#
# Idempotent, and additive rather than authoritative: the file is rewritten preserving any
# other entries, so this package never owns unrelated preloads. The write goes through a
# temp file + rename because /etc/ld.so.preload is read by the loader on EVERY exec — a
# partially written list would be observed by whatever runs during the write.
set -e

LIB=/usr/lib/naros/libnaros-uname.so
PRELOAD=/etc/ld.so.preload
TMP="$PRELOAD.naros-tmp"

case "$1" in
  configure)
    # Belt and braces: never point the loader at a library that is not on disk.
    if [ ! -f "$LIB" ]; then
      echo "naros-identity: $LIB missing, not registering preload" >&2
      exit 0
    fi
    if [ -f "$PRELOAD" ] && grep -qxF "$LIB" "$PRELOAD"; then
      exit 0
    fi
    if [ -f "$PRELOAD" ]; then
      cat "$PRELOAD" > "$TMP"
    else
      : > "$TMP"
    fi
    echo "$LIB" >> "$TMP"
    chmod 0644 "$TMP"
    mv "$TMP" "$PRELOAD"
    ;;
esac

exit 0
