#!/bin/sh

echo "Loading profile for EUMETSAT station..."

alias idl='/tcenas/home/bin/IDL/idl87/bin/idl'
. /tcenas/home/bin/IDL/idl87/bin/idl_setup.bash
export PATH=/tcenas/home/bin/IDL/idl87/bin:${PATH}
# export PATH=/tcenas/home/jackson/local/bin:/tcenas/home/bin/IDL/idl87/bin:${PAPH}

############################################################################################
## core functions
############################################################################################

# Method used to log outputs to the console.
logDEBUG()
{
  local curtime=$(date +%D-%T)
  [ "$DEBUG" == "yes" ] && echo "$curtime: [DEBUG] $1"
}

# Method used to log outputs to the console.
logINFO()
{
  local curtime=$(date +%D-%T)
  echo "$curtime: [INFO] $1"
}

# Method used to log outputs to the console.
logERROR()
{
  local curtime=$(date +%D-%T)
  echo "$curtime: [ERROR] $1"
}

# Method used to throw an error
throw()
{
  logERROR "$1"
  echo "Press any key to exit..."
  read key
  exit 1
}

nv_update_profile()
{
	cd
	rm -f eum_profile.sh
	wget -q http://files.nervtech.org/public_scripts/eum_profile.sh
	. eum_profile.sh
	cd - > /dev/null
}

############################################################################################
## git functions
############################################################################################


gitCheckoutBranch()
{
	git checkout -b "$1" origin/$1
}

gitCreateBranch()
{
	git checkout -b "$1"
}

gitRemoveBranch()
{
	git remote prune origin
	git push --delete origin "$1"
	# force delete local branch:
	git branch -D "$1"	
}

gitPush()
{
	local br=`git rev-parse --abbrev-ref HEAD`
	git push -u origin $br
}

gitTag()
{
	git tag -a "$1" -m "Tag for $1" 
	git push --tags origin
}

gitCommit()
{
	local msg="$1"
	local dest_dir="$2"

	if [ "$dest_dir" != "" ]; then	
		# Check if the project dir is valid:
		[ -d "$dest_dir/.git" ] || throw "Invalid git repository folder $dest_dir. Commit operation cancelled."

		# check if we have a valid message:
		[ -z "$msg" ] && throw "Detected empty commit message. Commit operation cancelled."

		# Go into project folder:
		cd "$dest_dir"
	fi

	# add all the new files:
	git add -A .

	# Perform the actual commit:
	git commit -a -m "$msg"

	if [ "$dest_dir" != "" ]; then	
		# get back to current folder:
		cd - > /dev/null
	fi
}

############################################################################################
## T4 project functions
############################################################################################

t4_root_dir="/tcenas/home/roche/projects/resp_t4"
# t4_gui_cm_dir=$t4_root_dir/gui_cm
t4_gui_utils_dir=$t4_root_dir/gui_cm/utils
t4_msps_dir=$t4_root_dir/msps
t4_msps_analysis_dir=$t4_root_dir/msps_analysis
t4_gui_cm_dir=$t4_msps_analysis_dir/GUI_CM
t4_input_dir=$t4_root_dir/inputfiles
t4_proj_dir=$t4_root_dir/proj
t4_proj_build_dir=$t4_root_dir/proj_build
t4_proj_app_dir=$t4_root_dir/proj_app
t4_proj_test_dir=$t4_root_dir/proj_test
t4_proj_env_dir=$t4_root_dir/proj_env

t4_python=$HOME/local/python39/bin/python3
# t4_python=python3

export PYTHONHOME=$HOME/local/python39

# t4_msps_analysis_dir=/tcenas/proj/metgeo/mefuser/MSPS_DEV/backup/git/git_phil/msps_analysis

t4_home()
{
	cd $t4_root_dir
}

t4_update_idl_startup()
{
	cd
	rm -f idl_startup.pro
	wget -q http://files.nervtech.org/public_scripts/idl_startup.pro
	cd - > /dev/null
}

t4_gui_home()
{
	cd $t4_msps_analysis_dir
}

t4_update_input_files()
{
	t4_home
	wget -m -nH --cut-dirs=5 ftp://ftp.eumetsat.int/pub/EUM/out/RSP/Loredana/inputfiles
	cd - > /dev/null
}

t4_download_input_files()
{
	cd $HOME
	# wget http://files.nervtech.org/public_scripts/MODI-AQU-MSP-CM_20070912100500_20070912101000.nc
	# wget http://files.nervtech.org/public_scripts/MODI-AQU-MSP-CM_20080223095500_20080223100000.nc
	# wget http://files.nervtech.org/public_scripts/SGA1-VII-GPP-CM_20070912084303_20070912084805.nc
	# wget http://files.nervtech.org/public_scripts/SGA1-VII-GPP-CM_20070912103900_20070912104403.nc
	cd - > /dev/null
}

t4_run_gui_cm()
{
	t4_update_gui_cm_pro

	cd $t4_gui_cm_dir/src
	# cd $t4_msps_analysis_dir/GUI_CM/src
	# export GUI_CM_INPUT_DIR=$t4_input_dir
	# export GUI_CM_DERIVED_CM_DIR=$t4_input_dir/for_current_version/MODIS_CM/derived
	# export GUI_CM_TRUE_CM_DIR=$t4_input_dir/for_current_version/MODIS_CM/true
	# export GUI_CM_L1B_DIR=$t4_input_dir/for_current_version/MODIS_L1B
	# export GUI_CM_MOD06_TPL_FILE=$t4_input_dir/for_current_version/MODIS_CM/true/mod06_template.str
	# export GUI_CM_RTTOV_FILE=$t4_input_dir/for_current_version/MODIS_L1B/rtcoef_eos_2_modis.dat
	# export GUI_CM_RTTOV_FILE=/tcenas/proj/metgeo/mefuser/MSPS_DEV/RTTOV/rttov_113/rtcoef_rttov11/rttov9pred54L/rtcoef_eos_2_modis.dat
	# export GUI_CM_ROOT_DIR=$t4_gui_cm_dir
	# export GUI_CM_MSPS_ANALYSIS_DIR=$t4_msps_analysis_dir
	
	export IDL_STARTUP=$HOME/idl_startup.pro

	# local madir=$t4_msps_analysis_dir
	# local madir=/tcenas/proj/metgeo/mefuser/MSPS_DEV/backup/git/git_loredana/msps_analysis
	local mspsdir=$t4_msps_dir
	# local mspsdir=/tcenas/proj/metgeo/mefuser/MSPS_DEV/backup/git/git_loredana/msps

	# export IDL_PATH=+/tcenas/home/bin/IDL/idl87/lib:+$t4_gui_cm_dir/utils:+$t4_msps_analysis_dir/MGUI/src:+$t4_msps_analysis_dir/GUI_CLOUDS/src:+$t4_msps_dir/src/idl
	# export IDL_PATH=+/tcenas/home/bin/IDL/idl87/lib:+$t4_gui_cm_dir/utils:+$t4_msps_analysis_dir/MGUI/src:+$t4_msps_analysis_dir/GUI_CLOUDS/src:+$t4_msps_dir/src/idl
	# export IDL_PATH=+/tcenas/home/bin/IDL/idl87/lib:+$madir/MGUI/src:+$madir/GUI_CLOUDS/src:+$mspsdir/src/idl
	# export IDL_PATH=+/tcenas/home/bin/IDL/idl87/lib:+$t4_msps_analysis_dir/MGUI/src:+$t4_msps_analysis_dir/GUI_CLOUDS/src:+$mspsdir/src/idl
	export IDL_PATH=+/tcenas/home/bin/IDL/idl87/lib:+$t4_msps_analysis_dir:+$mspsdir/src/idl:+$t4_gui_utils_dir

	export GUI_CM_CRM_DEFAULT_DIR=$t4_input_dir

	# idl -e gui_cm -args $t4_input_dir/for_updated_version/MODI-AQU-MSP-CM_20070912100500_20070912101000.nc
	# idl -e gui_cm -args /tcenas/proj/metgeo/mefuser/MSPS_DEV/dynamic_data/VII/CLD/for_gui_cm/MODI-AQU-MSP-CM_20070912100500_20070912101000.nc
	idl -e gui_cm -args /tcenas/proj/metgeo/mefuser/MSPS_DEV/dynamic_data/VII/CLD/for_gui_cm/SGA1-VII-GPP-CM_20070912084303_20070912084805.nc
	# idl -e gui_cm 
	cd - > /dev/null
}

t4_run_idl()
{
	t4_update_gui_cm_pro

	cd $t4_gui_cm_dir/src
	
	export IDL_STARTUP=$HOME/idl_startup.pro

	local mspsdir=$t4_msps_dir
	export IDL_PATH=+/tcenas/home/bin/IDL/idl87/lib:+$t4_msps_analysis_dir:+$mspsdir/src/idl:+$t4_gui_utils_dir

	export GUI_CM_CRM_DEFAULT_DIR=$t4_input_dir

	idl
}

t4_proj_update_test_gtoc()
{
	mkdir -p $t4_proj_test_dir
	cd $t4_proj_test_dir
	rm -f test_gtoc.py
	rm -f gtoc.py
	wget -q http://files.nervtech.org/public_scripts/test_gtoc.py
	wget -q http://files.nervtech.org/public_scripts/gtoc.py
	cd - > /dev/null
}

t4_update_gui_cm_pro()
{
	cd $t4_gui_cm_dir/src
	files=(gui_cm.pro gui_load_cm.pro read_cm_dataset.pro handle_draw_button.pro crm_save.pro 
		   roi_build_gui.pro crm_build_gui.pro show_granule_stats.pro update_roi_scene_mask.pro
		   update_skill_scores.pro gui_cm_plot_xs.pro get_granule_stats.pro flip_arrays.pro
		   crm_load.pro save_statistics.pro copy_pixmap.pro get_state.pro read_config.pro load_config.pro gui_cm.json build_cbm.pro
		   apply_scene_selection.pro select_draw_image.pro read_gui_cm_scales.pro show_cbm_build_gui.pro
		   show_scenes_help.pro show_tests_help.pro show_scaling_help.pro)

	# earth_mercator.jpg

	for f in "${files[@]}"
	do
		echo "Updating $f..."
		rm -f $f
		wget -q http://files.nervtech.org/public_scripts/$f
	done
	cd - > /dev/null
}

t4_proj_gtoc_test()
{
	t4_proj_update_test_gtoc
	t4_proj_activate_env

	cd $t4_proj_test_dir
	python3 test_gtoc.py "$@"
	cd - > /dev/null
	t4_proj_deactivate_env
}

t4_proj_create_venv()
{
	$t4_python -m venv $t4_proj_env_dir

	t4_proj_activate_env
	pip3 install --upgrade pip
	pip3 install numpy
}

t4_proj_activate_env()
{
	source $t4_proj_env_dir/bin/activate
}

t4_proj_deactivate_env()
{
	deactivate
}

t4_proj_home()
{
	cd $t4_proj_dir
}

t4_proj_checkout()
{
	git clone ssh://git@gitlab.nervtech.org/EUMETSAT/resp_t4_proj.git $t4_proj_dir
}

t4_proj_configure()
{
	t4_proj_home
	./autogen.sh

	mkdir -p $t4_proj_build_dir
	cd $t4_proj_build_dir
	export PKG_CONFIG_PATH=$HOME/local/libtiff/lib64/pkgconfig
	export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$HOME/local/sqlite/lib64/pkgconfig
	# $t4_proj_dir/configure --prefix=$t4_proj_app_dir CPPFLAGS="-I$HOME/local/include" LDFLAGS="-L$HOME/local/lib"  LIBS="-lsqlite3"
	$t4_proj_dir/configure --prefix=$t4_proj_app_dir --without-curl
}

t4_proj_build()
{
	cd $t4_proj_build_dir
	make
	make install
}

t4_proj_test()
{
	cd $t4_proj_build_dir
	make check
}

t4_build_lzma()
{
	# Build libtiff:
	cd $HOME/builds
	if [ ! -e "xz-5.2.5.tar.gz" ]; then
		wget https://tukaani.org/xz/xz-5.2.5.tar.gz
	fi

	rm -Rf xz-5.2.5
	tar xvfz xz-5.2.5.tar.gz
	cd xz-5.2.5
	./configure --prefix=$HOME/local/lzma
	make
	make install
	cd
}

t4_build_tiff()
{
	# Build libtiff:
	# requires lzma
	cd $HOME/builds
	if [ ! -e "tiff-4.1.0.tar.gz" ]; then
		echo "Downloading libtiff 4.1.0 sources..."
		wget http://download.osgeo.org/libtiff/tiff-4.1.0.tar.gz
	fi

	rm -Rf tiff-4.1.0
	tar xvfz tiff-4.1.0.tar.gz
	cd tiff-4.1.0
	./configure --prefix=$HOME/local/libtiff --with-lzma-include-dir=$HOME/local/lzma/include --with-lzma-lib-dir=$HOME/local/lzma/lib64
	make
	make install
	cd
}

t4_build_sqlite()
{
	# Build sqlite:
	cd $HOME/builds
	if [ ! -e "sqlite-autoconf-3340000.tar.gz" ]; then
		echo "Downloading sqlite-autoconf-3340000 sources..."
		wget https://sqlite.org/2020/sqlite-autoconf-3340000.tar.gz
	fi

	rm -Rf sqlite-autoconf-3340000
	tar xvfz sqlite-autoconf-3340000.tar.gz
	cd sqlite-autoconf-3340000
	./configure --prefix=$HOME/local/sqlite
	make
	make install
	cd
}


t4_build_readline()
{
	# Build readline:
	cd $HOME/builds
	if [ ! -e "readline-8.0.tar.gz" ]; then
		echo "Downloading readline 8.0 sources..."
		wget ftp://ftp.gnu.org/gnu/readline/readline-8.0.tar.gz
	fi

	rm -Rf readline-8.0
	tar xvfz readline-8.0.tar.gz
	cd readline-8.0
	./configure --prefix=$HOME/local/readline --enable-static --disable-shared
	make
	make install
	cd
}

t4_build_termcap()
{
	# Build termcap:
	cd $HOME/builds
	if [ ! -e "termcap-1.3.1.tar.gz" ]; then
		echo "Downloading termcap 1.3.1 sources..."
		wget https://ftp.gnu.org/gnu/termcap/termcap-1.3.1.tar.gz
	fi

	rm -Rf termcap-1.3.1
	tar xvzf termcap-1.3.1.tar.gz
	cd termcap-1.3.1/
	./configure --prefix=$HOME/local/termcap
	make
	make install
	cd
}

t4_build_openssl()
{
	# Build openssl:
	cd $HOME/builds
	if [ ! -e "openssl-1.0.2o.tar.gz" ]; then
		echo "Downloading openssl-1.0.2o sources..."
		wget https://www.openssl.org/source/openssl-1.0.2o.tar.gz
	fi

	rm -Rf openssl-1.0.2o
	tar xvzf openssl-1.0.2o.tar.gz
	cd openssl-1.0.2o/
	./config --prefix=$HOME/local/ssl --openssldir=$HOME/local/ssl shared zlib
	make
	make install
	cd
}

# Building python 3.9 from sources:
t4_build_python()
{
	# Build python:
	cd $HOME/builds
	if [ ! -e "Python-3.9.1.tgz" ]; then
		echo "Downloading Python-3.9.1 sources..."
		wget https://www.python.org/ftp/python/3.9.1/Python-3.9.1.tgz
	fi

	rm -Rf Python-3.9.1
	tar xvzf Python-3.9.1.tgz
	cd Python-3.9.1/
	export PKG_CONFIG_PATH=$HOME/local/ssl/lib/pkgconfig:$HOME/local/readline/lib64/pkgconfig
	export CPPFLAGS="-I$HOME/local/readline/include"
	export LDFLAGS="-L$HOME/local/readline/lib64 -L$HOME/local/termcap/lib"

	./configure --with-openssl=$HOME/local/ssl --prefix=$HOME/local/python39 --with-ensurepip=install --libdir=$HOME/local/python39/lib

	for m in _struct binascii unicodedata _posixsubprocess pyexpat _md5 _sha1 _sha256 _sha512 _sha3 select _random _socket zlib fcntl _blake2 _csv _contextvars array math _elementtree _pickle _datetime _zoneinfo _bisect _heapq _asyncio _json _statistics readline; do 
		sed -i "s/^#\(${m}\)/\1/" Modules/Setup; 
	done

	echo "_ssl _ssl.c -DUSE_SSL -I$HOME/local/ssl/include -I$HOME/local/ssl/include/openssl -L$HOME/local/ssl/lib -lssl -lcrypto" >> Modules/Setup

	make
	make install

	# Install support for virtualenv creation:
	$HOME/local/python39/bin/pip3 install virtualenv
	cd
}

t4_build_all()
{
	t4_build_lzma
	t4_build_tiff
	t4_build_sqlite
	t4_build_openssl
	t4_build_readline
	t4_build_termcap
	t4_build_python
}

echo "Done loading EUMETSAT statin profile."