#!/bin/bash
# shellcheck disable=SC2090,SC2086,SC2089,SC1091
#! Default project path
PROJECT_PATH="$HOME/projects/mt_dao"

#! Parse command-line options
if ! OPTIONS=$(getopt -o p: --long project_path: -n 'parse-options' -- "$@"); then
	echo "mt_dao_base.sh: Error parsing options" >&2
	exit 1
fi

eval set -- "$OPTIONS"

while true; do
	case "$1" in
	-p | --project_path)
		PROJECT_PATH="$2"
		shift 2
		;;
	--)
		shift
		break
		;;
	*)
		break
		;;
	esac
done

#! Get the date and time
DATETIME=$(date '+%Y%m%d_%H%M%S')
mkdir -p "$mt_dao_SAVE_PATH"/"$DATETIME"
SUPERNODE_CLIENTAPP_ID="${CUDA_VISIBLE_DEVICES//,/-}"

#! Get ClientApp API address
MASTER_IP=$(hostname -I | awk '{print $1}')
CLIENTAPP_API_PORT=$(uv run python -c "from mt_dao.port_utils import get_free_tcp_port; print(get_free_tcp_port())")
export CLIENTAPP_API_ADDRESS=${MASTER_IP}:${CLIENTAPP_API_PORT}

#! Launch Supernode
if [[ -n $mt_dao_LAUNCHER_NO_SUPERNODE ]]; then
	echo "mt_dao_base.sh: mt_dao_LAUNCHER_NO_SUPERNODE is set, so skipping Supernode launch."
else
	CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES . "$PROJECT_PATH"/scripts/base_launchers/supernode.sh -p "$PROJECT_PATH"
	echo "clientapp.sh: Flower Supernode started, ID: CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES}."
fi

#! If the env variable CLIENTAPP_NO_RELOAD is set, then do not reload the clientapp
if [[ -n $CLIENTAPP_NO_RELOAD ]]; then
	echo "clientapp.sh: CLIENTAPP_NO_RELOAD is set."
	CLIENTAPP_NO_RELOAD="--no-reload"
fi

#! Launch ClientApp
FLWR_HOME=$PROJECT_PATH uv run flwr-clientapp $CLIENTAPP_NO_RELOAD \
	--insecure \
	--clientappio-api-address $CLIENTAPP_API_ADDRESS >"$mt_dao_SAVE_PATH"/"$DATETIME"/clientapp_${SUPERNODE_CLIENTAPP_ID}.log 2>&1 &

sleep 5

echo "clientapp.sh: Flower ClientApp started, ID: ${SUPERNODE_CLIENTAPP_ID}."
