#!/bin/sh -e

# Copy into "usr/root" any files needed by a Linux "usr/contents.txt" file.
# This shell script should be run in a Linux build directory.
#
# The contents.txt file may have source paths that start
# with "usr/root/", in which case we copy those files from
# "$TILERA_ROOT/tile/" into "usr/root/" as we go, stripping any Elf files.
# All other paths may be relative paths (relative to the root of the
# Linux build directory) or absolute.

# Verify the current directory.
if [ ! -f usr/contents.txt ]; then
    echo "$0 should be run in a Linux build dir with usr/contents.txt" >&2
    exit 1
fi

# Verify the "install" directory.
if [ -n "$TILERA_ROOT" ]; then
    if [ ! -f "$TILERA_ROOT"/bin/tile-gcc ]; then
	echo "TILERA_ROOT must point to a per-chip hierarchy of an MDE install tree." >&2
	exit 1
    fi
    PREFIX="$TILERA_ROOT/tile"
    CROSS_COMPILE="$TILERA_ROOT/bin/tile-"
else
    case "`uname -m`" in
	tile*) ;;
	*) echo "TILERA_ROOT not set in environment." >&2; exit 1 ;;
    esac
    PREFIX=
    CROSS_COMPILE=
fi

exec < usr/contents.txt
while read type linux_path source_path rest; do
    case $type-$source_path in file-usr/root/*)
	mde_path=${source_path#usr/root/}
	mkdir -p ${source_path%/*}
	magic=`file $PREFIX/$mde_path | awk '{print $2}'`
	if [ $magic = ELF ]; then
	    echo "  STRIP   $source_path"
	    ${CROSS_COMPILE}strip "$@" -o $source_path $PREFIX/$mde_path
	else
	    echo "  INSTALL $source_path"
	    cp $PREFIX/$mde_path $source_path
	    chmod +w $source_path
	fi
    esac
done
