#!/bin/bash
#
# Copy dynamically linked libraries for a binary, so we can assemble a Docker
# image.
#
# Run with:
#   copy-libraries /path/to/binary /output/dir
#
# Dependencies:
# - awk
# - cp
# - grep
# - ldd
# - mkdir

set -o errexit
set -o nounset
set -o pipefail

# Path to a Linux binary that we're going to run in the container.
binary_path="${1}"
# Path to directory to write the output to.
output_dir="${2}"

exe_name=$(basename "${binary_path}")

# Identify linked libraries.
libraries=($(ldd "${binary_path}" | awk '{print $(NF-1)}' | grep -v '=>'))
# Add /bin/sh, which we need for Docker imports.
libraries+=('/bin/sh')

mkdir -p "${output_dir}"

# Copy executable and all needed libraries into temporary directory.
cp "${binary_path}" "${output_dir}/${exe_name}"
for lib in "${libraries[@]}"; do
    mkdir -p "${output_dir}/$(dirname "$lib")"
    # Need -L to make sure we get actual libraries & binaries, not symlinks to
    # them.
    cp -L "${lib}" "${output_dir}/${lib}"
done
