#!/bin/bash

#
# Auto-generate requirements for executables (both ELF and a.out) and library
# sonames, script interpreters, and perl modules.
#

ulimit -c 0

# Read the newline separated file list from stdin into an array, verbatim,
# and keep it quoted at every use below.  The list used to be "sanitised" by
# backslash-escaping a partial set of shell metacharacters and then re-used
# in unquoted expansions; that both mangled legitimate file names (the
# backslashes leaked into the paths handed to rpmdeps and find-requires.ksyms)
# and left word splitting, pathname expansion and shell metacharacter
# re-interpretation wide open for every character the escape set missed
# (IFS whitespace, "$", "`", "|", "&", ";", "<", ">", "(", ")", "#", "~", ...).
# A quoted array needs no escaping at all: file names are data, never code.
# Blank lines are dropped, which is exactly what the old $(...) command
# substitution and unquoted expansions used to do with them (and what
# find-requires.ksyms' grep does anyway).
mapfile -t filelist < <(grep -v '^[[:blank:]]*$')

[ -x /usr/lib/rpm/rpmdeps -a "${#filelist[@]}" -gt 0 ] && \
    printf '%s\n' "${filelist[@]}" | /usr/lib/rpm/rpmdeps --requires

#
# --- Kernel module imported symbols
#
# Since we don't (yet) get passed the name of the package being built, we
# cheat a little here by looking first for a kernel, then for a kmod.
#

unset is_kmod

# Match kernel modules and /boot paths with in-process ERE instead of
# spawning two seds per file.  The regexes are verbatim copies of the old
# sed programs, and the [ -n "${BASH_REMATCH[n]}" ] checks replicate the old
# behaviour exactly: sed only printed the captured group, so a match with an
# empty capture produced no output and [ -n ] failed.  bash =~ and sed -r
# follow the same POSIX ERE leftmost-longest capture rules, so the captured
# groups agree and so does the boolean result.
re_kmod='^.*/lib/modules/(.*)/(.*)\.ko(\.gz|\.bz2|\.xz)?$'
re_boot='^.*/boot/(.*)'
for f in "${filelist[@]}"; do
    if [[ $f =~ $re_kmod ]] && [ -n "${BASH_REMATCH[2]}" ]; then
        is_kmod=1
    elif [[ $f =~ $re_boot ]] && [ -n "${BASH_REMATCH[1]}" ]; then
        unset is_kmod
        break
    fi
done

[ -x /usr/lib/rpm/openEuler/find-requires.ksyms ] && [ "$is_kmod" ] &&
    printf "%s\n" "${filelist[@]}" | /usr/lib/rpm/openEuler/find-requires.ksyms

exit 0
