#!/usr/bin/env bash
#--------------------------------------------------------------------------------#
# This file is part of the PALM model system.
#
# PALM is free software: you can redistribute it and/or modify it under the terms
# of the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
#
# PALM is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# PALM. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 1997-2021  Leibniz Universitaet Hannover
# Copyright 2020-2022  pecanode GmbH
#--------------------------------------------------------------------------------#
# project install script
#--------------------------------------------------------------------------------#
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
   DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
   SOURCE="$(readlink "$SOURCE")"
   [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPT_LOCATION="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

project_root_dir=$(readlink -f "${SCRIPT_LOCATION}/")
project_bin_dir=$(readlink -f "${project_root_dir}/bin/")
project_build_dir=$(readlink -f "${project_root_dir}/build/")
project_lib_dir=$(readlink -f "${project_root_dir}/lib/")
project_share_dir=$(readlink -f "${project_root_dir}/share/")
project_src_dir=$(readlink -f "${project_root_dir}/src/")

install_prefix="${project_build_dir}"

program_name="PALM model"

if command -v nf-config &> /dev/null
then
    fortran_compiler="$(nf-config --fc)"
elif command -v nc-config &> /dev/null
then
    fortran_compiler="$(nc-config --fc)"
fi

install_function() {
   printf "### %s\n" "Installing ${program_name} ..."
   if [ "${do_clean}" == "true" ]; then
      rm -r ${install_prefix}/MAKE_DEPOSITORY_default
   fi
   mkdir -p ${install_prefix}
   cd ${install_prefix}
   install_bin_dir=${install_prefix}/bin
   mkdir -p ${install_bin_dir}
   chmod a+x $(realpath "${project_bin_dir}/batch_scp")
   for executable in "palmbuild" "palmconfigure" "palm_cti" "palmdoxygen" "palmrun" "palmtest"; do
      chmod a+x $(realpath "${project_bin_dir}/${executable}")
      ln -s -f $(realpath --relative-to="${install_bin_dir}" "${project_bin_dir}/${executable}") ${install_bin_dir}
   done
   bash ${project_bin_dir}/palmconfigure \
        -p "${install_prefix}" \
        ${fortran_compiler:+-c }${fortran_compiler} \
        ${netcdf_c_prefix:+-s }${netcdf_c_prefix} \
        ${netcdf_fortran_prefix:+-t }${netcdf_fortran_prefix}

   # build TenStream
   tenstream_prefix="${install_prefix}/tenstream"
   if [ "${build_tenstream:-false}" == "true" ]; then
     source ${project_build_dir}/tenstream/.tenstream_build_options
     bash ${project_lib_dir}/tenstream/install \
       -b "${tenstream_prefix}/build" \
       -p "${tenstream_prefix}/" \
       -c "${TENSTREAM_FORTRAN_COMPILER:-}" \
       -o "${TENSTREAM_COMPILER_OPTIONS:-}" \
       -l "${TENSTREAM_LINKER_OPTIONS:-}" \
       ${do_clean:+-x }
   fi

   # build rrtmg
   rrtmg_prefix="${install_prefix}/rrtmg"
   source ${project_build_dir}/rrtmg/.rrtmg_build_options
   bash ${project_lib_dir}/rrtmg/install \
        -b "${rrtmg_prefix}/build" \
        -p "${rrtmg_prefix}" \
        -c ${RRTMG_FORTRAN_COMPILER} \
        -o "${RRTMG_COMPILER_OPTIONS}" \
        -l "${RRTMG_LINKER_OPTIONS}" \
        ${do_clean:+-x }

   # configure palm with externals
   bash ${project_bin_dir}/palmconfigure \
        -p "${install_prefix}" \
        ${fortran_compiler:+-c }${fortran_compiler} \
        ${netcdf_c_prefix:+-s }${netcdf_c_prefix} \
        ${netcdf_fortran_prefix:+-t }${netcdf_fortran_prefix} \
        -r "${rrtmg_prefix}" \
        -T "${tenstream_prefix}"

   bash ${project_bin_dir}/palmbuild -v -c "default"
   if [ ! -d ${HOME}/.palm ]; then
      mkdir -p ${HOME}/.palm
   fi
   if [ ! -f ${HOME}/.palm/palmtest.yml ]; then
      mv ${install_prefix}/palmtest.yml ${HOME}/.palm/palmtest.yml
   else
      mv ${install_prefix}/palmtest.yml ${HOME}/.palm/palmtest__$(date +"%Y-%m-%d__%H:%M:%S,%3N").yml
   fi
   printf "### %s\n" "Installing ${program_name} finished."
}

show_usage() {
   echo "Usage: $0 [-h] [-p <install_prefix>] [-c <compiler>] [-s <path>] [-t <path>] [-T] [-x]"
}

show_help() {
   show_usage
   echo "      -h                     show this help message"
   echo "      -p <install_prefix>    set installation directory"
   echo "      -c <compiler>          set desired compiler"
   echo "      -s <path>              set existing NetCDF-C library installation prefix (helps to find library)"
   echo "      -t <path>              set existing NetCDF-Fortran library installation prefix (helps to find library)"
   echo "      -T                     build with TenStream radiative transfer solver"
   echo "      -x                     clean already existing build files"
}

while getopts ":p:c:s:t:hTx" o; do
   case "${o}" in
      p)
         install_prefix="$(readlink -m "${OPTARG}")"
         ;;
      c)
         fortran_compiler="${OPTARG}"
         ;;
      s)
         netcdf_c_prefix="$(readlink -e "${OPTARG}")"
         ;;
      t)
         netcdf_fortran_prefix="$(readlink -e "${OPTARG}")"
         ;;
      T)
         build_tenstream="true"
         ;;
      x)
         do_clean="true"
         ;;
      h)
         show_help
         exit 0
         ;;
      *)
         show_usage
         exit 1
         ;;
   esac
done
# strip all parsed options from the options list
shift $((OPTIND-1))

install_function
