#!/bin/bash

if [ -n "$CAS_SERVER" ]; then
	echo "$CAS_SERVER"
fi

. $(dirname "$0")/fuse.sh
. $(dirname "$0")/fuse-basic.sh

if [ -n "$CAS_SERVER" ]; then
	. $(dirname "$0")/cas.sh
	# We also expect download start/end time with cas server
	EXPECTED_FIELDS=4
else
	EXPECTED_FIELDS=2
fi

decode_protoc() {
	protoc --proto_path="${PROTO_PATH}" \
		--decode=build.bazel.remote.execution.v2.ExecutedActionMetadata \
		"${PROTO_PATH}/build/bazel/remote/execution/v2/remote_execution.proto" \
		<"$TMPDIR/$TIMES"
}

count_fields() {
	# should be 4 lines per field (title, secs, nanos and closing })
	expected_lines=$(($1 * 4))
	if [ $(decode_protoc | wc -l) != $expected_lines ]; then
		echo "Expected $1 fields and $expected_lines lines" >&2
		decode_protoc
		exit 1
	fi
}

mkdir "$TMPDIR/cas-remote"
REF="$TMPDIR/reference"
mkdir "$REF"

# start cas server and buildbox
if [[ -n "$CAS_SERVER" ]]; then
	start_cas_server
fi
start_buildbox

base "$ROOT"
create_file "$ROOT"

restart_buildbox

stop_buildbox
if [[ -n "$CAS_SERVER" ]]; then
	stop_cas_server
fi

# Now check that expected number of fields have been written out
count_fields $EXPECTED_FIELDS
