#!/bin/bash

set -eu

# wait for buildgrid
sleep 10

apt-get update && apt-get install jq -y

mkdir -p /tmp/upload/input1;
test_date=$(date +'%s')
echo "#!/bin/bash
echo $test_date
" > /tmp/upload/input1/hello.sh;

chmod +x /tmp/upload/input1/hello.sh;

# The first build
/usr/local/bin/trexe --remote=http://controller:50051 \
    --input-path=/tmp/upload/input1 --output-path=output \
    --result-metadata-file=/tmp/result1.json "./hello.sh"

if [[ $(jq ".actionResultMetadata.cachedResult" /tmp/result1.json) != "false" ]]; then
    exit 1
fi

# The second build should observe the cache hit
OUTPUT=$(/usr/local/bin/trexe --remote=http://controller:50051 --no-wait \
    --input-path=/tmp/upload/input1 --output-path=output \
    --result-metadata-file=/tmp/result2.json "./hello.sh");
echo "Output: ${OUTPUT}"

if [[ $(jq ".actionResultMetadata.cachedResult" /tmp/result2.json) != "true" ]]; then
    exit 1
fi

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