#!/bin/bash

if [ -z "$CAS_SERVER" ]; then
	echo "Missing buildbox-casd path" >&2
	exit 1
fi

remote_cleanup() {
	stop_cas_server
	cleanup
}
trap remote_cleanup INT TERM EXIT

start_cas_server() {
	if ! [ -x "$(command -v netstat)" ]; then
		echo "netstat is required for running network tests" >&2
		exit 1
	fi
	"$CAS_SERVER" --bind localhost:0 "$TMPDIR/cas-remote" &
	CAS_SERVER_PID=$!
	PORT=
	local TIMEOUT=10
	local START=$SECONDS
	while [ -z $PORT ]; do
		sleep 0.1
		# Check if the process is still running
		if ! [ -e /proc/$CAS_SERVER_PID ]; then
			echo "CAS server process $CAS_SERVER_PID has terminated."
			exit 1
		fi
		local ELAPSED=$((SECONDS - START))
		PORT=$(netstat -lntp 2>/dev/null | grep "LISTEN.* $CAS_SERVER_PID" | head -n 1 | sed -e 's/.*:\([0-9]\+\).*/\1/')
		# Check if the timeout has been reached
		if [ $ELAPSED -ge $TIMEOUT ]; then
			echo "Timeout reached: Failed to detect open port for CAS server process $CAS_SERVER_PID within $TIMEOUT seconds."
			exit 1
		fi
	done
	REMOTE_ARGS="--remote=http://localhost:$PORT"
	if [ -n "$PREFETCH" ]; then
		REMOTE_ARGS="$REMOTE_ARGS --prefetch"
	fi
}

stop_cas_server() {
	if [ -n "$CAS_SERVER_PID" ]; then
		kill $CAS_SERVER_PID
		local TIMEOUT=10
		local START=$SECONDS

		# Wait for buildbox-casd to terminate with timeout
		while [ -e "/proc/$CAS_SERVER_PID" ]; do
			sleep 0.1
			local ELAPSED=$((SECONDS - START))

			# Check if the timeout has been reached
			if [ $ELAPSED -ge $TIMEOUT ]; then
				echo "Timeout reached: buildbox-casd process $CAS_SERVER_PID did not terminate within $TIMEOUT seconds."
				exit 1
			fi
		done

		CAS_SERVER_PID=
	fi
}
