#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-case-attach TEST_CASE_ID FILE [MIME_TYPE]"
    echo ""
    echo "Attach FILE to the test case TEST_CASE_ID."
}

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

TEST_CASE_ID="$1"
shift
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
if [ -z "$TEST_CASE_ID" ]; then
    usage
    exit 1
fi

# $LAVA_RESULT_DIR is set by lava-test-shell
case_attachment_dir="$LAVA_RESULT_DIR/results/$TEST_CASE_ID/attachments/$(dirname $FILE)"
mkdir -p "$case_attachment_dir"
SIZE=`stat --format="%s" $FILE`
if [ $SIZE -gt 26214400 ]; then
    echo "$FILE is too large, skipping"
else
    cp "$FILE" "$case_attachment_dir"
    if [ ! -z "$MIMETYPE" ]; then
        echo "$MIMETYPE" > "$case_attachment_dir/$(basename $FILE).mimetype"
    fi
fi
