#!/bin/sh
# Deregister the identity shim from /etc/ld.so.preload before its files are removed
# (NAROS.md §2.3), so the loader never names a library that is no longer on disk.
#
# Runs on remove/deconfigure only: on `upgrade` the entry must persist, since the
# replacement .so lands at the same path and the new postinst is a no-op.
set -e

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

case "$1" in
  remove | deconfigure)
    [ -f "$PRELOAD" ] || exit 0
    # grep exits 1 when nothing survives the filter; that is the empty case, not an error.
    grep -vxF "$LIB" "$PRELOAD" > "$TMP" || true
    if [ -s "$TMP" ]; then
      chmod 0644 "$TMP"
      mv "$TMP" "$PRELOAD"
    else
      # An empty ld.so.preload is legal but pointless — drop the file entirely.
      rm -f "$TMP" "$PRELOAD"
    fi
    ;;
esac

exit 0
