#!/bin/bash -e
##
# Check linking of a user app to check only allowed shared libraries are referenced.
#
# The list is short on purpose: these binaries are downloaded and run on
# machines we know nothing about, so anything they need has to be inside them.
# libcurl used to be the exception -- it was linked dynamically, which meant
# allowing its whole dependency chain (krb5, openldap, nghttp2 and the rest)
# through this check as well.  The build image now provides a static libcurl,
# so none of that belongs on the list any more.  refs #38153
##
set -beEu -o pipefail

if [[ $# = 0 ]] ; then
    echo "Wrong # args $0 prog [...]"
    exit 1
fi

function checkProg() {
    local prog="$1"

    ldd $prog | awk -v prog="$prog" '
         /statically linked/ {
             next;  # nothing dynamic to check
         }
         /linux-vdso\.so|libc\.so|libgcc_s\.so|libdl\.so|libm\.so|ld-linux.*\.so/ {
             next;  # the only shared libraries a userApp is allowed to use
         }
         {
            print prog, "found unallowed dynamic library:", $0 > "/dev/stderr";
            errcnt += 1
         }
         END {
             if (errcnt) {
                exit 1;
             }
         }'
}


for p in "$@" ; do
    checkProg "$p"
done
