#!/bin/sh

set -eu

# chroot helper

if [ $# -ne 2 ]; then
	echo "Usage: $0 /full/path/to/bin /path/to/chroot"
	exit 1
fi

PROG=$1
CHROOT=$2

if [ ! -d ${CHROOT} ]; then
	echo "${CHROOT}: not a directory"
	exit 1
fi

if [ ! -w ${CHROOT} ]; then
	echo "${CHROOT}: not writable"
	exit 1
fi

if [ ! -f ${PROG} ]; then
	echo "${PROG}: not a file"
	exit 1
fi

if [ ! -x ${PROG} ]; then
	echo "${PROG}: not executable"
	exit 1
fi

OPSYS=$(uname)
UNLINK=

case $(file ${PROG}) in
*statically*)
	FILES=${PROG}
	;;
*dynamically*)
	case "${OPSYS}" in
	OpenBSD)
		FILES=$(ldd ${PROG} | awk '$7 ~ /^\// { print $7 }')
		;;
	FreeBSD)
		FILES=$(ldd -a -f '%p\n' ${PROG} | grep '^/.*[0-9]$' | sort -u)
		FILES="/libexec/ld-elf.so.1 ${FILES} ${PROG}"
		;;
	NetBSD)
		FILES=$(ldd -f '%p\n' ${PROG})
		;;
	DragonFly)
		FILES=$(ldd -a -f '%p\n' ${PROG} | grep -v ':$' | sort -u)
		FILES="/libexec/ld-elf.so.2 ${FILES} ${PROG}"
		UNLINK="-U"
		;;
	*) echo "Sorry, '${OPSYS}' is not yet supported by '$0'" && exit 1
	esac
esac

FILES=$(echo $FILES | sed -e 's, /, ,'g -e 's,^/,,')

tar czf - -C / ${FILES} | tar xzf - -C ${CHROOT}/ ${UNLINK}
# vim:set sw=4 sts=4 ts=4 :
