#!/bin/bash

if [ -z "$TMT_TEST_PIDFILE" ]; then
    echo "tmt-file-submit can be used only in the context of a running test."
    exit 1
fi

set -o errexit -o pipefail -o noclobber -o nounset

die() { echo "$*" >&2; exit 2; }  # complain to STDERR and exit with error
needs_arg() { if [ -z "$OPTARG" ]; then die "No arg for --$OPT option"; fi; }

check_opt_args () {
    local OPTIND
    while getopts T:l:filename:s:server:port-: OPT; do
        # support long options: https://stackoverflow.com/a/28466267/519360
        if [ "$OPT" = "-" ]; then   # long option: reformulate OPT and OPTARG
            OPT="${OPTARG%%=*}"       # extract long option name
        fi
        case "$OPT" in
            filename )       needs_arg; eval "FILENAME=\"\$$OPTIND\"" ; OPTIND=$((OPTIND+1)) ;;
            l )              needs_arg; FILENAME=$OPTARG ;;
            s )              continue;;
            T )              continue;;
            server )         OPTIND=$((OPTIND+1));;
            port )           OPTIND=$((OPTIND+1));;
        esac
    done
    shift $((OPTIND-1)) # remove parsed options and args from $@ list
}

if [ $# -eq 2 ]; then
    FILENAME=$2
elif [ $# -gt 2 ]; then
    check_opt_args "$@"
fi

# Some files are already present in test invocation path, no need to
# copy them into test data directory as well
if [ -e "$TMT_TEST_INVOCATION_PATH/$(basename "$FILENAME")" ]; then
    echo "File '$FILENAME' already stored in '$TMT_TEST_INVOCATION_PATH'.";
    realpath -s --relative-to="$TMT_TEST_DATA" "$FILENAME" >> "$TMT_TEST_SUBMITTED_FILES"
else
    [ -d "$TMT_TEST_DATA" ] || mkdir -p "$TMT_TEST_DATA"
    cp -f "$FILENAME" "$TMT_TEST_DATA";

    echo "File '$FILENAME' stored to '$TMT_TEST_DATA'.";
    basename "$FILENAME" >> "$TMT_TEST_SUBMITTED_FILES"
fi
