#! /bin/sh

REPORT_DIR="/home/spice3/codecoverage"

ensure_report_dir() {
  if [[ ! -e $REPORT_DIR ]]; then
	mkdir $REPORT_DIR
	chown -R spice3:spice3 $REPORT_DIR
  fi
}

case "$1" in
  start)
	echo "Starting CodeCoverage collector."
	ensure_report_dir

	TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
	COMMAND_START="dotnet /opt/dotnet/dotnet-coverage/dotnet-coverage.dll collect \
		--session-id 73c34ce5-501c-4369-a4cb-04d31427d1a4 \
		--output $REPORT_DIR/report-$TIMESTAMP.coverage \
		--server-mode \
		--background \
		--log-file $REPORT_DIR/log-$TIMESTAMP.log \
		--log-level Verbose"
	capsh --user=spice3 -- -c "$COMMAND_START"
	;;
  stop)
	echo "Stopping CodeCoverage collector."
	COMMAND_STOP="dotnet /opt/dotnet/dotnet-coverage/dotnet-coverage.dll shutdown 73c34ce5-501c-4369-a4cb-04d31427d1a4 --log-level Verbose"
	timeout 15s capsh --user=spice3 -- -c "$COMMAND_STOP"
	;;
  merge)
	echo "Merging all reports."
	dotnet /opt/dotnet/dotnet-coverage/dotnet-coverage.dll merge $(ls "$REPORT_DIR"/*.coverage) --output "$REPORT_DIR/merged.cobertura" --output-format cobertura	
	;;
  clear)
	echo "Clearing code coverage data."
	if [[ -e $REPORT_DIR ]]; then
		rm $REPORT_DIR/*
	else
		ensure_report_dir
	fi
	;;
  *)
	echo "Usage: /etc/init.d/spice3_codecoverage {start|stop|merge|clear}"
	exit 1
esac

exit 0

# Note: I do not know why `capsh --user=spice3` is necessary. It does not appear to be a permission issue, but rather about the owner, i.e., 
# `chmod -R 766`-ing the FIFO's parent directory did not do the trick. Further, the instrumented RTB stats the pipe as `0` and not as `-1 EACCES`.
# The instrumented RTB does not even attempt to open the FIFO if the owner != spice3. I could not find anything in the instrumentation logic, so its
# either a Linux thing or maybe .NET is doing some shenanigans when working with FIFO instead of just open/write.
# To fix this, the pipe has to either be `chown`ed to spice3, or the `dotnet-coverage` tool must be ran as spice3 user instead of root.