################################################################################
#
# Check NETCDF environments
#
################################################################################

# If SCALE_NETCDF_LIBS variable is not set, nc-config (and nf-config) command is used.
# the command can be specified with SCALE_NC_CONFIG and SCALE_NF_CONFIG variables.

ifeq ($(SCALE_NETCDF_LIBS),)

  # check nc-config
  ifeq ($(SCALE_NC_CONFIG),)
    ifeq ($(shell nc-config --help > /dev/null 2>&1 && echo OK),OK)
      SCALE_NC_CONFIG=nc-config
    else
      $(error nc-config command is not found. You need to set PATH for nc-config or set SCALE_NETCDF_LIBS and SCALE_NETCDF_INCLUDE variables appropriately)
    endif
  else
    ifeq ($(shell $(SCALE_NC_CONFIG) --libs > /dev/null 2>&1 || echo NG),NG)
      $(error SCALE_NC_CONFIG variable is set: "$(SCALE_NC_CONFIG)". However, failed to execute it)
    endif
  endif

  # check fortran support
  ifeq ($(SCALE_NF_CONFIG),)
    ifeq ($(shell nf-config --help > /dev/null 2>&1 && echo OK),OK)
      SCALE_NF_CONFIG=nf-config
    else
      ifeq ($(shell $(SCALE_NC_CONFIG) --flibs 2> /dev/null |grep unknown > /dev/null 2>& 1 && echo OK),OK)
        $(warning nf-config command is not found and nc-config command does not support fortran.)
        $(warning NetCDF-fortran is required for the net2g and scale-gm.)
        $(warning If you need them, you need to set PATH for nf-config or set SCALE_NETCDF_LIBS and SCALE_NETCDF_INCLUDE variable appropriately)
      else
        SCALE_NF_CONFIG=$(SCALE_NC_CONFIG)
      endif
    endif
  else
    ifeq ($(shell $(SCALE_NF_CONFIG) --flibs > /dev/null 2>&1 || echo NG),NG)
      $(error SCALE_NF_CONFIG variable is set: "$(SCALE_NF_CONFIG)". However, failed to execute it)
    endif
  endif

  ifneq ($(SCALE_NF_CONFIG),)
    SCALE_NETCDF_LIBS=$(shell $(SCALE_NF_CONFIG) --flibs) $(shell $(SCALE_NC_CONFIG) --libs)
    ifeq ($(SCALE_NETCDF_INCLUDE),)
      SCALE_NETCDF_INCLUDE=$(shell $(SCALE_NF_CONFIG) --fflags) $(shell $(SCALE_NC_CONFIG) --cflags)
    endif
  endif

else

  ifeq ($(SCALE_NETCDF_INCLUDE),)
    $(warning SCALE_NETCDF_LIBS is set, but SCALE_NETCDF_INCLUDE is not set)
  endif

endif


# for the netcdf-fortran package of Fedra and Cent OS
ifneq ($(shell ls /etc/redhat-release 2> /dev/null),)
  ifeq ($(SCALE_SYS),Linux64-gnu-ompi)
    SCALE_NETCDF_INCLUDE += -I/usr/lib64/gfortran/modules
  endif
endif


checknetcdf:
	@echo SCALE_NETCDF_LIBS    : $(SCALE_NETCDF_LIBS)
	@echo SCALE_NETCDF_INCLUDE : $(SCALE_NETCDF_INCLUDE)
	@echo SCALE_NC_CONFIG      : $(SCALE_NC_CONFIG)
	@echo SCALE_NF_CONFIG      : $(SCALE_NF_CONFIG)
