#!/bin/bash

# ============================================================================
# @author <sylvain.herledan@oceandatalab.com>
# @author <ziad.khoury.hanna@oceandatalab.com>
# @date 2024-11-08
#
# Install the Python and SEAScope software components required to follow the
# Ocean Training Course 2025 interactive lectures.
# ============================================================================

set -o nounset
set -o errexit
set -o pipefail

main()
{
	local DIR;
	DIR="$(pwd)";

	if [ "${DIR}" == "${HOME}" ]; then
		DIR="${DIR}/OTC25-workspace"
		mkdir -p "${DIR}"
	fi

	cd "${DIR}"
	echo '1. Downloading resources...'
	curl -fsSL https://ftp.odl.bzh/odl/events/otc25/software/_/macos_$(arch)-otc25-bundle.tar.gz \
	 | tar xzf -

	echo '2. Installing python packages...'
	"${DIR}/.python/bin/python" -m venv envOTC25
	set +o nounset
	source "envOTC25/bin/activate"
	set -o nounset
	python -m pip install -U pip
	python -m pip install --no-cache-dir python-env-otc2025
	python -m pip install --no-cache-dir "${DIR}/eumartools_benloveday-0.0.1.tar.gz"
	rm "${DIR}/eumartools_benloveday-0.0.1.tar.gz"
	python -c "exec(\"import re\nwith open('${DIR}/envOTC25/lib/python3.12/site-packages/fluxengine/core/fe_setup_tools.py', 'r') as f:\n\ta=f.read()\n\na=re.sub(r'\\\bgetargspec\\\b', 'getfullargspec', a)\nwith open('${DIR}/envOTC25/lib/python3.12/site-packages/fluxengine/core/fe_setup_tools.py', 'w') as f:\n\tf.write(a)\n\n\")"
	python -c "exec(\"import re\nwith open('${DIR}/envOTC25/lib/python3.12/site-packages/fluxengine/tools/reanalyse_fco2/v2_f_conversion.py', 'r') as f:\n\ta=f.read()\n\na=re.sub(r'\\\bnumpy.int\\\b', 'int', a)\na=re.sub(r'\\\bnumpy.float\\\b', 'float', a)\na=re.sub(r'\\\bnp.int\\\b', 'int', a)\na=re.sub(r'\\\bnp.float\\\b', 'float', a)\nwith open('${DIR}/envOTC25/lib/python3.12/site-packages/fluxengine/tools/reanalyse_fco2/v2_f_conversion.py', 'w') as f:\n\tf.write(a)\n\n\")"

	echo "cd '${DIR}'; source '${DIR}/envOTC25/bin/activate'; \$SHELL" > "${DIR}/Terminal"
	chmod +x "${DIR}/Terminal"

	echo ''
	echo '3. Installation complete'
	echo "The OTC25 workspace is located at: ${DIR}"
	echo ''
	echo 'You can now double-click on:'
	echo '  * "Terminal" to start a terminal pre-configured with the OTC25 environment'
	open "${DIR}"
}
main
exit 0
