# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

# ----------------------------------------------------------------------------
# If you submit this package back to Spack as a pull request,
# please first remove this boilerplate and all FIXME comments.
#
# This is a template package file for Spack.  We've put "FIXME"
# next to all the things you'll want to change. Once you've handled
# them, you can save this file and test your package like this:
#
#     spack install dwd-icon-tools
#
# You can edit this file again by typing:
#
#     spack edit dwd-icon-tools
#
# See the Spack documentation for more information on packaging.
# ----------------------------------------------------------------------------

from spack.package import *
import os
from urllib.parse import urlparse


class DwdIconTools(Package):
    """DWD Icon Tools"""

    homepage = "https://gitlab.dkrz.de/dwd-sw/dwd_icon_tools.git"
    # maintainers("oriol.tinto")

    git = "https://gitlab.dkrz.de/dwd-sw/dwd_icon_tools.git"

    token = os.environ.get('SPACK_ICON_NWP_GITTOKEN')
    if token is not None:
        parsed = urlparse(git)
        user = 'token'
        password = token
        git = "{}://{}:{}@{}/{}".format(parsed.scheme, user, password, parsed.netloc, parsed.path)

    version("2.5.3", branch="icontools-2.5.3")
    version("2.5.2", branch="icontools-2.5.2")

    depends_on("netcdf-c")
    depends_on("netcdf-fortran")
    depends_on("eccodes+tools")
    depends_on("libxml2")

    #
    @staticmethod
    def init_submodules():
        # Run git submodule update
        git = which("git")
        git("submodule", "update", "--init", "--recursive")

    def setup_build_environment(self, env):
        # Some environment variables to set
        if self.spec.satisfies("%gcc"):
            env_variables_to_set = {
                "CXXFLAGS": "-O2 -g -fopenmp -Wunused -DNOMPI",
                "FCFLAGS": "-I/usr/include --std=f2008 -O2 -g -cpp -fopenmp -fbounds-check -Wunused -DNOMPI",
                "LIBS": f"-leccodes -lgfortran -lhdf5 -lxml2",
            }
        elif self.spec.satisfies("%intel"):
            # Intel
            env_variables_to_set = {
                "CXXFLAGS": "-O2 -g -qopenmp -Wunused -DNOMPI",
                "FCFLAGS": "-I/usr/include -stand f08 -O2 -g -fpp -qopenmp -check bounds -Wunused -DNOMPI",
                "CFLAGS": "-std=gnu99 -O3 -DHAVE_LIBNETCDF -DHAVE_NETCDF4 -DHAVE_CF_INTERFACE -DHAVE_LIBGRIB "
                          "-DHAVE_LIBGRIB_API -DpgiFortran -D__ICON__ -DHAVE_CONFIG_H -traceback",
                "LIBS": f"-leccodes -lgfortran -lhdf5 -lxml2",
                "V": "1",
                "VERBOSE": "1",
                "LDFLAGS": "-Wl,--copy-dt-needed-entries",
            }
        else:
            raise AssertionError("Compiler does not match gcc nor intel")

        for variable, value in env_variables_to_set.items():
            env.set(variable, value)

    def install(self, spec, prefix):
        options = [
            f"--prefix={prefix}",
            "--with-eccodes=yes",
            "--enable-grib2",
            "--enable-iso-c-interface",
            "--enable-static",
            "--disable-shared",
            f"--with-netcdf={spec['netcdf-c'].prefix}"
        ]

        self.init_submodules()
        configure(*options)
        make()
        make("install")