#!/bin/bash

module unload python
module unload python3
module load python3

set -eux

if [[ -z ${1} ]];then
  echo "Please specify the version to update"
  false
fi
mod_version=${1}

if [[ $# -gt 0 ]]; then shift; fi
hosts=${@:-deploy@aa-login deploy@ab-login deploy@ac-login deploy@ad-login}

assets_version=$mod_version

echo "module version to be installed: $mod_version"
echo "on hosts: $hosts"

# Where is pyg2p source code
src_dir=$PWD
src_host=$HOST
src_host=hpc-login

# where to install it

dest_dir=/usr/local/apps/pyg2p/$mod_version
eccodes=ecmwf-toolbox/2025.04.0.0
for dest_host in $hosts; do


    case $dest_host in

        deploy@a?-login ) dest_dir=/usr/local/apps/pyg2p/$mod_version
             static_data_root=/usr/local/apps/pyg2p/data
             eccodes=ecmwf-toolbox/2025.04.0.0 ;;
        *   )  echo  "unexpected target host $dest_host"; false ;;
    esac

    echo installing pyg2p/$mod_version in $dest_host ....
    if ssh -x $dest_host [[ -d $dest_dir ]]; then
        case $mod_version in
            *dev* | *test | 3.2.8 | 3.0.0-01 | 3.0.1 | 3.0.0.post1 ) echo "reinstalling pyg2p/$mod_version" ;;
            * ) echo "module pyg2p/$mod_version is already installed on $dest_host. skipping."; continue ;;
        esac
    fi
    ssh -x $dest_host bash -l << END
        set -eux
        module unload hdf5 python3 python gdal grib_api eccodes netcdf4 || :
        module load python3/3.12.9-01
        umask 022
        python_version=\$(python3 -c "import sys; print(f'python{sys.version_info.major}.{sys.version_info.minor}')")
        mkdir -p ${dest_dir}/lib/\${python_version}/site-packages/pyg2p/configuration/ $src_dir/configuration/global/
        rsync -avz --exclude='.git/' -e ssh $src_host:$src_dir/configuration/global/intertables.json ${dest_dir}/pyg2p/configuration/
        rsync -avz --exclude='.git/' -e ssh $src_host:$src_dir/configuration/global/intertables.json ${dest_dir}/lib/\${python_version}/site-packages/pyg2p/configuration/
        rsync -avz --exclude='.git/' -e ssh $src_host:$src_dir/configuration/global/geopotentials.json ${dest_dir}/pyg2p/configuration/
        rsync -avz --exclude='.git/' -e ssh $src_host:$src_dir/configuration/global/geopotentials.json ${dest_dir}/lib/\${python_version}/site-packages/pyg2p/configuration/
        rsync -avz --exclude='.git/' -e ssh $src_host:$src_dir/configuration/global/parameters.json ${dest_dir}/pyg2p/configuration/
        rsync -avz --exclude='.git/' -e ssh $src_host:$src_dir/configuration/global/parameters.json ${dest_dir}/lib/\${python_version}/site-packages/pyg2p/configuration/
END
    echo done
done
