#!/bin/bash
# Created by Ben Okopnik on Wed May 20 18:14:22 CDT 2009

[ "$UID" -eq 0 ] || { echo "You need to run this as root."; exit 1; }

[ -z "$1" ] && { printf "${0##*/} <program_to_install>\n"; exit; }

source .chrootrc

# prog=`echo $1|cut -d' ' -f 1`
prog="$1"
shift
args="$@"
# args=`echo $1|cut -d' ' -f 2-`
full=`which $prog`

[ -f "$full" ] || { printf "'$prog' not found in PATH.\n"; exit; }

# Hack of the Day: list, via "strace", all the files that the app opens
# successfully; this is the most reliable way to get as complete of a list
# as possible. The arg to this func can be a little tricky, though, since
# some programs don't exit when executed - meaning that "strace" will never
# exit either. As a result, all progs need to be launched in some way
# that will make them exit; see "list-install" in this directory for lots
# of usable examples.
for file in $(strace -s 1024 -eopen $full $args 2>&1|awk -F'"' '/[0-9]$/{print $2}')
do
	# Skip device files, security-sensitive system files, and users' private files
	if [ -n "`echo $file|egrep '/proc/|/dev/|/etc/passwd|/etc/shadow|/etc/group|~/home'`" ]
	then
		echo "Skipping $file"
		continue
	fi
	echo "Copying $file to $dir$file"

	# Create the target dir if it doesn't exist
	targetdir=${file%/*}
	[ -d "$dir$targetdir" ] || mkdir -p "$dir$targetdir"

	if [ -f "$dir$file" ]
	then
		echo "$file already present; skipping..."
		continue
	else
		# Copy, and: preserve links/mode/ownership/timestamps; update only;
		# force if necessary; follow symlinks in source.
		cp -aufL "$file" "$dir$file"
		echo $file
	fi
done

# Find man pages, install them if they exist
# Strip out any extensions
b=${prog%%.*}
# Strip all the path info
bare=${b##*/}
m=`man -w $bare`
if [ $? -eq 0 ]
then
	# Look for a manpage for the progname without any extensions
	mb=${m%%.*}
	# Strip off the path info
	mbare=${mb##*/}
	# Get the path for the manpage installation
	mpath=${m%/*}
	# ...and get the extension as well, since we'll need to add it back on
	mext=${m#*.}

	# If the manpage filename doesn't equal the progname (e.g. 'awk' and
	# 'gawk'), then install the 'linked' manpage by following the link and
	# saving the endpoint under the original name. Weird solution - but it
	# works well as long as we don't need to update or relink the manpages
	# (as we would in a real distro.)
	if [ "$bare" != "$mbare" ]
	then
		[ -d "$dir/$mpath" ] || mkdir -p "$dir/$mpath"
		echo "Copying $mpath/$bare.$mext to $dir/$mpath/$bare.$mext"
		cp -fL "$mpath/$bare.$mext" "$dir/$mpath/$bare.$mext"
	else
		tdir=${m%/*}
		[ -d "$dir$tdir" ] || mkdir -p "$dir$tdir"
		echo "Copying $m to $dir/$m"
		cp -fL "$m" "$dir/$m"
	fi
fi

echo "Copying $full to $dir$full"
cp -fL $full $dir$full

