#!/bin/bash

set -eu
# wait for buildgrid
sleep 10

mkdir -p /tmp/upload/input/a
mkdir -p /tmp/upload/input/b
mkdir -p /tmp/upload/input/c/baz

echo "foo" >/tmp/upload/input/a/foo.txt
echo "bar" >/tmp/upload/input/b/bar.txt
echo "baz" >/tmp/upload/input/c/baz/baz.txt

echo "#!/bin/bash
cat foo.txt
cat bar.txt
cat baz/baz.txt
" >/tmp/upload/input/test.sh

chmod +x /tmp/upload/input/test.sh

/usr/local/bin/trexe --remote=http://controller:50051 --stdout-file=/tmp/stdout --skip-cache-lookup \
    --input-path=/tmp/upload/input/a/foo.txt --input-path=/tmp/upload/input/b/bar.txt \
    --input-path=/tmp/upload/input/c --input-path=/tmp/upload/input/test.sh \
    "./test.sh"

out=$(</tmp/stdout)
expected=$(printf "foo\nbar\nbaz")

if [[ "$out" != "$expected" ]]; then
    diff <(echo $out) <(echo "$expected")
    exit 1
fi

mkdir -p /tmp/upload/input/script
echo "#!/bin/bash
cat a/foo.txt
cat b/bar.txt
cat c/baz/baz.txt
" >/tmp/upload/input/script/test.sh

chmod +x /tmp/upload/input/script/test.sh

# test uploading inputs with remappings
/usr/local/bin/trexe --remote=http://controller:50051 --stdout-file=/tmp/stdout --skip-cache-lookup \
    --input-path=/tmp/upload/input/a/foo.txt:a/foo.txt --input-path=/tmp/upload/input/b/bar.txt:b/bar.txt --input-path=/tmp/upload/input/c:/c/baz/.. \
    --input-path=/tmp/upload/input/script/:./ ./test.sh

out=$(</tmp/stdout)
expected=$(printf "foo\nbar\nbaz")

if [[ "$out" != "$expected" ]]; then
    diff <(echo $out) <(echo "$expected")
    exit 1
fi
