#!/bin/sh

# usage destpath filename

# Recursively grab an executable and all the libraries needed to run it.
# Source paths beginning with / will be copied into destpath, otherwise
# the file is assumed to already be there and only its library dependencies
# are copied.

function mkchroot
{
  [ $# -lt 2 ] && return


  dest=$1
  shift
  for i in "$@"
  do
    if [ ! "${i:0:1}" == "/" ]
    then
      x=$(which $i)
      [ -z "$x" ] || i="$x"
    fi

    [ -f "$dest/$i" ] && continue
    if [ -e "$i" ]
    then
      echo $i
      d=`echo "$i" | grep -o '.*/'`
      ([ -z "$d" ] || mkdir -p "$dest/$d") &&
      cat "$i" > "$dest/$i" &&
      chmod +x "$dest/$i"
    else
      echo "Not found: $i"
    fi
    mkchroot "$dest" $(ldd "$i" | egrep -o '/.* ')
  done
}

mkchroot "$@"
