# The following has been extracted and modified for our use under an MIT 
# license by Stephen Gaito on 2019/NOV/25
#
# The original was taken from:
# https://raw.githubusercontent.com/AppImage/pkg2appimage/master/functions.sh
# (commit ID ed1d385282a6aa6c9a93b52296f20555adf9bae7 commited 2019/Apr/9)
# 
# The original copyright was: Copyright (c) 2004-16 Simon Peter
#

# Copy the library dependencies of all exectuable files in the current 
# directory (it can be beneficial to run this multiple times)
#
copy_deps()
{
  PWD=$(readlink -f .)
  FILES=$(find . -type f -executable -or -name *.so.* -or -name *.so	\
          | sort | uniq )

  for FILE in $FILES ; do
    ldd "${FILE}" | grep "=>" | awk '{print $3}'	\
    | xargs -I '{}' echo '{}' >> DEPSFILE
  done
 
 DEPS=$(cat DEPSFILE | sort | uniq)

  for FILE in $DEPS ; do
    if [ -e $FILE ] && [[ $(readlink -f $FILE)/ != $PWD/* ]] ; then
      cp -v --parents -rfL $FILE ./ || true
    fi
  done
  rm -f DEPSFILE
}

# Delete blacklisted files. Our blacklisted files are the shared libraries 
# extracted from the "base" docker image
# 
delete_blacklisted()
{
  docker run --rm -it --entrypoint=find $DOCKER_FROM -iname "*.so.*"		\
    | xargs -i basename {} | sed 's/\r//g' | sed 's/\(so\.[0-9]\+\).*$/\1/'	\
    | sort | uniq > BLACKLISTED_FILES

  for FILE in $(cat BLACKLISTED_FILES | tr "\r\n" "  ") ; do
    FILES="$(find . -name "${FILE}*" -not -path "./usr/optional/*")"
    for FOUND in $FILES ; do
      rm -vf "$FOUND" "$(readlink -f "$FOUND")"
    done
  done

  rm BLACKLISTED_FILES

  # Do not bundle developer stuff
  rm -rf usr/include || true
  rm -rf usr/lib/cmake || true
  rm -rf usr/lib/pkgconfig || true
  find . -name '*.la' | xargs -i rm {}
}

