#!/bin/bash
#
# copyfail-shim-disable
#   Remove /usr/lib64/no-afalg.so from /etc/ld.so.preload.
#
# Idempotent. Leaves other entries in ld.so.preload untouched.

set -eu

SHIM=/usr/lib64/no-afalg.so
PRELOAD=/etc/ld.so.preload

err()  { printf 'copyfail-shim-disable: %s\n' "$*" >&2; }
info() { printf 'copyfail-shim-disable: %s\n' "$*"; }

if [ "$(id -u)" -ne 0 ]; then
    err "must run as root"
    exit 2
fi

if [ ! -f "$PRELOAD" ]; then
    info "no $PRELOAD on disk - nothing to do"
    exit 0
fi

if ! grep -Fxq "$SHIM" "$PRELOAD"; then
    info "$SHIM not present in $PRELOAD - nothing to do"
    exit 0
fi

# Atomic update via tempfile + rename(2).
tmp=$(mktemp /etc/ld.so.preload.XXXXXX)
trap 'rm -f "$tmp"' EXIT

grep -Fxv "$SHIM" "$PRELOAD" > "$tmp" || true

# If the result is empty, remove the file entirely so glibc skips the
# preload codepath rather than mmap'ing an empty file every exec.
if [ ! -s "$tmp" ]; then
    rm -f "$PRELOAD"
    rm -f "$tmp"
    trap - EXIT
    info "disabled and removed empty $PRELOAD"
    exit 0
fi

chmod 0644 "$tmp"
mv -f "$tmp" "$PRELOAD"
trap - EXIT

info "disabled: $SHIM removed from $PRELOAD"
exit 0
