#!/bin/bash

set -eu

dim="32x32x39"
base_args="-name LMDZ -netcdf 0 -arch_dir /home/abarral/PycharmProjects/installLMDZ/script_install/arch_local -arch local-gfortran-parallel_ -d $dim"  # those don't appear in the folder name (except dim)
file_to_check="LMDZ/modipsl/modeles/LMDZ/BENCH$dim/restart.nc"
base_path="/tmp/comp_bench/"
local=$(pwd)

function do_bench() {
  local rev=$1
  local path=$2
  local install_args=$3
  if [[ -f "$path/$file_to_check" ]]; then return; fi

  rm -rf "$path"
  mkdir -p "$path" && cd "$path"

  cp "$local/install_lmdz.sh" .

  local logf="comp.log"
  local install_cmd="./install_lmdz.sh $base_args $install_args -r $rev"
  echo "Running <$install_cmd> [log: $(pwd)/$logf]"
  $install_cmd &> $logf
}

function comp_bench() {
  local rev1=$1
  local rev2=$2
  local install_args=$3
  local path1="$base_path/r${rev1}_d${dim}_${install_args// /_}"
  local path2="$base_path/r${rev2}_d${dim}_${install_args// /_}"

  do_bench "$rev1" "$path1" "$install_args"
  do_bench "$rev2" "$path2" "$install_args"

  if cmp "$path1/$file_to_check" "$path2/$file_to_check" &>/dev/null; then
    echo "All good ! for r$rev1/r$rev2=$install_args"
  else
    echo ":( nope for r$rev1/r$rev2=$install_args"
  fi
}

function comp_full() {
  local rev1=$1
  local rev2=$2

  # Check all combinations
  for rad in "oldrad" "rrtm" "ecrad"; do
  for veget in "none" "CMIP6"; do
  for para in "none" "mpi_omp"; do
    comp_bench "$rev1" "$rev2" "-rad $rad -parallel $para -veget $veget -compilephysiq lmd"
  done; done; done

  # Check some additional params on sparse configs
  comp_bench "$rev1" "$rev2" "-xios -rad oldrad -parallel $para -veget none -compilephysiq lmd"  # xios
  for para in "none" "mpi_omp"; do
    comp_bench "$rev1" "$rev2" "-cosp v1 -rad oldrad -parallel $para -veget none -compilephysiq lmd"  # cosp v1 (no v2 because broken atm)
    comp_bench "$rev1" "$rev2" "-debug -rad oldrad -parallel $para -veget none -compilephysiq lmd"  # debug
  done

  # 1D
  dim="79"
  file_to_check="LMDZ/modipsl/modeles/LMDZ/BENCH$dim/restartphy.nc"
  comp_bench "$rev1" "$rev2" "-rad oldrad -parallel none -veget none -compilephysiq lmd -d $dim"

  # Iso
  dim="48x36x39"
  file_to_check="LMDZ/modipsl/modeles/LMDZ/BENCH$dim/restart.nc"
  for para in "none" "mpi_omp"; do
    comp_bench "$rev1" "$rev2" "-rad oldrad -parallel $para -veget none -compilephysiq lmdiso -d $dim"
  done
}

#comp_bench 4938 4946 "-rad oldrad -parallel mpi_omp -veget none -compilephysiq lmd"
#comp_bench 4938 4946 "-rad ecrad -parallel mpi_omp -veget none -compilephysiq lmd"
#comp_bench 4938 4946 "-rad ecrad -parallel none -veget none -compilephysiq lmd"
#comp_bench 4950 4946 "-rad oldrad -parallel none -veget none -compilephysiq lmd"

comp_full 5017 5155






