Commit df64ada8 authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Refactor collect-binaries to work on any file, link or directory

parent cea3c094
Loading
Loading
Loading
Loading
+41 −13
Original line number Diff line number Diff line
#!/bin/bash
# Copyright (c) 2020 Dom Sekotill <dom.sekotill@kodo.org.uk>
# Copyright (c) 2020, 2022 Dom Sekotill <dom.sekotill@kodo.org.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
@@ -48,17 +48,19 @@ missing() {

copy() {
	test -e ${STAGE:=$DEFAULT_STAGE}/$1 && return
	local dest=$STAGE/$(dirname $1)
	mkdir -p $dest
	if [[ -h $1 ]]; then
		ln -s $(readlink $1) $dest/$(basename $1)
		copy $(readlink -f $1) $dest
		copy_link "$1"
	elif [[ -d $1 ]]; then
		copy_dirs "$1"
	else
		cp $1 $dest/
		case $(head -c4 "$1") in
			?ELF) copy_elf "$1" ;;
			*) copy_file "$1" ;;
		esac
	fi
}

copy_bin() {
copy_elf() {
	local bin=$1
	ldd "$bin" | while read dep; do
		local dep=${dep% (*}
@@ -67,11 +69,37 @@ copy_bin() {
			/*) ;;
			*) continue ;;
		esac
		copy $dep
		copy "$dep"
	done || true
	copy $bin
	copy_file "$bin"
}

copy_link() {
	copy_dirs "$(dirname "$1")"
	ln -s $(readlink "$1") "$STAGE/$1"
	copy "$(readlink -f "$1")"
}

copy_file() {
	copy_dirs "$(dirname "$1")"
	cp "$1" "$STAGE/$1"
}

copy_dirs() {
	[[ $1 -ef / ]] && mkdir -p "$STAGE" && return
	[[ -e $STAGE/$1 ]] && return
	if [[ -h $1 ]]; then
		copy_link "$1"
	elif [[ -d $1 ]]; then
		copy_dirs "$(dirname "$1")"
		mkdir "$STAGE/$1"
	else
		echo >&2 "$1 does not appear to be a directory"
		exit 2
	fi
}


trap missing EXIT

declare -a TARGETS=()
@@ -87,15 +115,15 @@ until [[ $# -eq 0 ]]; do
done

if [[ ${#TARGETS[*]} -gt 0 ]]; then
	for bin in "${TARGETS[@]}"; do
		copy_bin "$bin"
	for target in "${TARGETS[@]}"; do
		copy "$target"
	done
else
	[[ -t 0 ]] && cat <<-END_TXT >&2
		No files specified in arguments; are you sure you meant to do that?
		Reading files list from terminal input:
	END_TXT
	while read bin; do
		copy_bin "$bin"
	while read target; do
		copy "$target"
	done
fi