#NOTE the lava_test_shell_action fills in the proper interpreter path
# above during target deployment

# basename is not present on AOSP builds, but the /*\// thing does not
# work with dash (Ubuntu builds) or busybox (OpenEmbedded).  Both of
# those have basename though.
type basename > /dev/null || basename () { echo ${1/*\//}; }
type dirname > /dev/null || dirname () { dn=${1%\/*}; bn=$(basename $1); [ "${dn}" = "${bn}" ] && echo "." || echo $dn; }

usage () {
    echo "Usage: lava-test-run-attach FILE [MIME_TYPE]"
    echo ""
    echo "Attach FILE to the current test run."
}

if [ $# -ne 1 -a $# -ne 2 ]; then
    usage
    exit 1
fi

FILE="$1"
shift
MIMETYPE="$1"

if [ -z "$FILE" ]; then
    usage
    exit 1
fi
if [ ! -f "$FILE" ]; then
    echo "File $FILE not found"
    exit 1
fi

# $LAVA_RESULT_DIR is set by lava-test-shell
attachment_dir="$LAVA_RESULT_DIR/attachments/$(dirname $FILE)"
mkdir -p "$attachment_dir"
cp "$FILE" "$attachment_dir"
if [ ! -z "$MIMETYPE" ]; then
    echo "$MIMETYPE" > "$attachment_dir/$(basename $FILE).mimetype"
fi
