#!/bin/sh -eu
# ###########################################################################
#             Thomas Dreibholz's R Simulation Scripts Collection
#                  Copyright (C) 2005-2025 Thomas Dreibholz
#
#               Author: Thomas Dreibholz, thomas.dreibholz@gmail.com
# ###########################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

# ====== Check parameters ===================================================
if [ $# -lt 1 ] ; then
   echo >&2 "Usage: get-libs [Program] [Libs Directory]"
   exit 1
fi

PROGRAM="$1"
if [ $# -gt 1 ] ; then
   LIBSDIR="$2"
else
   LIBSDIR="lib.$PROGRAM"
fi


# ====== Get library names ==================================================
lddFile="$(mktemp -t get-libs.XXXXXXXXXX)"
trap 'rm -f $lddFile' EXIT
env LANG=C ldd "$PROGRAM" >"$lddFile" || exit 1

LIBS_NOT_FOUND=$(awk -F " " '{ if( ($3 == "not") && ($4 == "found")) { print $1 } }' <"$lddFile")
LIBS=$(awk -F " " '{ if(length($3)>length($1)) { print $3 } }' <"$lddFile")
LOADER=$(awk -F " " '{ if(length($3)==0) { print $1 } }' <"$lddFile" | grep -v linux-vdso.so)

if [ "$LIBS_NOT_FOUND" != "" ] ; then
   echo >&2 "ERROR: Some shared libraries have not been found:"
   echo >&2 "$LIBS_NOT_FOUND"
   exit 1
fi

NUM_ENTRIES=$(grep -cv linux-vdso.so "$lddFile")
NUM_LIBS=$(echo "$LIBS" | xargs -n1 | wc --lines)
NUM_LOADER=$(echo "$LOADER" | xargs -n1 | wc --lines)

USED_ENTRIES=$((NUM_LIBS + NUM_LOADER))

if [ "$NUM_LOADER" -ne 1 ] || [ $USED_ENTRIES -ne "$NUM_ENTRIES" ] ; then
   (
      echo "ERROR: Something went wrong with shared library collection! Got unexpected ldd output!"
      echo "-----"
      cat "$lddFile"
      echo "NUM_LOADER=$NUM_LOADER"
      echo "NUM_LIBS=$NUM_LIBS"
      echo "-----"
   ) >&2
   exit 1
fi


# ====== Prepare library directory ==========================================
if [ -e "$LIBSDIR" ] ; then
   rm -rf "$LIBSDIR"
fi
mkdir "$LIBSDIR" || exit 1


# ====== Copy libraries =====================================================
for LIB in $LIBS ; do
   if [ -e "$LIB" ] ; then
      echo "   - $(wc -c "$LIB")"
      cp "$LIB" "$LIBSDIR" || exit 1
   fi
done
if [ -e "$LOADER" ] ; then
   cp "$LOADER" "$LIBSDIR"/ld-loader.so || exit 1
   echo "   - $(wc -c "$LOADER") (loader)"
fi
